简体   繁体   English

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

[英]create threads but don't run it immediately in linux

I am trying to execute my program in threads, I use pthread_create() , but it runs the threads immediately. 我试图在线程中执行程序,我使用pthread_create() ,但它会立即运行线程。 I would like to allow the user to change thread priorities before running. 我想允许用户在运行之前更改线程优先级。 How it is possible to resolve? 如何解决?

for(int i = 0; i < threads; i++)
{
   pthread_create(data->threads+i,NULL,SelectionSort,data);
   sleep(1);
   print(data->array);
}

Set the priority as you create the thread. 在创建线程时设置优先级。

Replace 更换

int local_errno;

local_errno = pthread_create(..., NULL, ...);
if (local_errno != 0) { ... }

with

int local_errno;

pthread_attr_t attr;
local_errno = pthread_attr_init(&attr);
if (local_errno != 0) { ... }

{
    struct sched_param sp;
    local_errno = pthread_attr_getschedparam(&attr, &sp);
    if (local_errno != 0) { ... }

    sp.sched_priority = ...;

    local_errno = pthread_attr_setschedparam(&attr, &sp);
    if (local_errno != 0) { ... }
}    

/* So our scheduling priority gets used. */
local_errno = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (local_errno != 0) { ... }

local_errno = pthread_create(..., &attr, ...);
if (local_errno != 0) { ... }

local_errno = pthread_attr_destroy(&attr);
if (local_errno != 0) { ... }

For pthreads the priority isn't set after thread creation but rather by passing suitable attributes upon thread creation: the thread attributes go where you have specified NULL in your pthread_create() call. 对于pthreads,优先级不是在创建线程之后设置的,而是在创建线程时传递适当的属性的:线程属性位于您在pthread_create()调用中指定NULL If you want to delay thread creation until the user has given you a priority you can create a function object expecting the priority and upon call of that function object you'd kick off the thread. 如果您要延迟线程的创建,直到用户给您一个优先级,您可以创建一个具有优先级的功能对象,并在调用该功能对象时启动线程。 Of course, you'll still need to keep track of the thus created object (possibly using a std::future<...> -like object) to later join that thread. 当然,您仍然需要跟踪由此创建的对象(可能使用类似std::future<...>的对象),以便以后加入该线程。

Note that providing an answer shouldn't be construed as endorsing thread priorities: as far as I can tell, playing with thread priorities are ill-advised. 请注意,提供答案不应解释为赞同线程优先级:据我所知,玩线程优先级是不明智的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM