创建线程,但不要立即在 Linux 中运行它
create threads but don't run it immediately in linux
我试图在线程中执行我的程序,我使用 pthread_create()
,但立即运行线程。我想允许用户在运行之前更改线程优先级。如何解决?
for(int i = 0; i < threads; i++)
{
pthread_create(data->threads+i,NULL,SelectionSort,data);
sleep(1);
print(data->array);
}
创建线程时设置优先级。
替换
errno = pthread_create(..., NULL, ...);
if (errno) { ... }
pthread_attr_t attr;
errno = pthread_attr_init(&attr);
if (errno) { ... }
{
struct sched_param sp;
errno = pthread_attr_getschedparam(&attr, &sp);
if (errno) { ... }
sp.sched_priority = ...;
errno = pthread_attr_setschedparam(&attr, &sp);
if (errno) { ... }
}
/* So our scheduling priority gets used. */
errno = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (errno) { ... }
errno = pthread_create(..., &attr, ...);
if (errno) { ... }
errno = pthread_attr_destroy(&attr);
if (errno) { ... }
对于pthreads,优先级不是在线程创建之后设置的,而是通过在线程创建时传递适当的属性:线程属性转到您在pthread_create()
调用中指定的NULL
的位置。如果要延迟线程创建,直到用户给予您优先级,则可以创建一个函数对象,以期待优先级和呼叫该函数对象,您会启动线程。当然,您仍然需要跟踪如此创建的对象(可能使用 std::future<...>
-like对象)以稍后加入该线程。
请注意,提供答案不应被解释为认可线程优先级:据我所知,播放线程优先级是不明智的。
相关文章:
- 如何在linux终端中同时编译和运行c++代码
- 函数在Windows或Linux上运行时表现不同
- 如何在CPP中创建应该在Windows和Linux上运行的套接字?
- 在 Linux 群集上运行 Windows C++代码
- [longjmp/setjmp]c++ 相同的代码窗口有异常 Linux 没有错误并且运行良好
- 有没有办法让我编写一个可以在Windows和Linux上运行的命令行游戏?
- 无法在 Linux 上运行C++ ZMQ 项目的可执行文件
- 我在使用 boost::serialization 时遇到了一个问题,我的代码在 Linux 中运行良好,但在 Wind
- 如果从脚本运行应用程序,则在 Linux 中使用 GDB
- 在 Linux 上C++:在作为 systemd 服务运行时侦听键盘输入
- 在 linux 原因上运行自定义原型插件
- 从Raspberry Pi / Linux上的Python脚本运行和停止C++程序
- 在 Linux 上没有 /proc/self/exe 的 C/C++ 运行时可执行文件的大小?
- C++ Linux 运行时basic_string::_M_construct null 无效错误
- Opendir() 在带有空格的名称上失败,在 Linux 上运行
- 在Windows上运行Linux Makefile(.so文件)
- 如何在 Linux 运行时检查堆栈使用情况?
- Netbeans C/C++ on Linux "step in to" Linux C 运行时代码?
- 在Linux运行时重写libstdc++搜索路径
- Linux - 运行 valgrind 时不会出现源文件/行