创建线程,但不要立即在 Linux 中运行它

create threads but don't run it immediately in linux

本文关键字:Linux 运行 线程 创建      更新时间:2023-10-16

我试图在线程中执行我的程序,我使用 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对象)以稍后加入该线程。

请注意,提供答案不应被解释为认可线程优先级:据我所知,播放线程优先级是不明智的。