使用 pthreads 在挂起模式下创建线程 [英] Create thread in suspended mode using pthreads

查看:93
本文介绍了使用 pthreads 在挂起模式下创建线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Win32中,可以通过将 dwCreationFlags 参数与CREATE_SUSPENDED一起使用来以挂起模式创建线程.我正在寻找与pthreads类似的功能.请注意,我不想在运行线程后再通过使用条件变量暂停该线程,而实际上是在暂停模式下创建它,然后稍后再启动它.

In Win32, you can create a thread in suspended mode, by using the dwCreationFlags parameter with CREATE_SUSPENDED. I am looking for a similar functionality with pthreads. Note that I don't want to suspend the thread after running it and then pausing it by using condition variables, but actually create it in suspended mode and then start it later on.

使用这种方法的优点是,我可以在运行该线程之前为其分配一些属性.例如,在启动之前将其绑定到某个核心,这比先启动然后将其分配给一个核心更有效,因为它可能会从一个核心转移到另一个核心.

The advantage of using this approach is that I can assign some properties to that thread before running it. For example, bind it to a certain core before starting, which is more efficient than first starting and then assigning it to a core, as it might get moved from one core to another.

如果不可能,在调用 pthread_create 时,我们至少可以将线程绑定到内核吗?

If not possible, can we at least bind a thread to a core when calling pthread_create?

推荐答案

如果要从一开始就将线程绑定到CPU,则可以将 pthread_create 的形式与一起使用> pthread_attr_t 参数.Linux支持特殊属性 pthread_attr_setaffinity_np ,这允许将线程绑定到特定的CPU集.请勿将其与需要运行线程的 pthread_setaffinity_np 混淆.

If you want to bind a thread to a CPU right from the start, you can use the form of pthread_create with a pthread_attr_t argument. Linux suports a special attribute pthread_attr_setaffinity_np, which allows the binding of a thread to a certain CPU set. Do not confuse this with pthread_setaffinity_np which requires an already running thread.

行动计划是这样的:

// create generic attribute set
pthread_attr_t attr;
pthread_attr_init(&attr);

// enhance with CPU set
pthread_attr_setaffinity_np(&attr, ...cpuset-args);

// create thread with right attributes including CPU set
pthread_t thread;
pthread_create(&thread, &attr, ...);

// viola, thread runns on given CPU-set, cleanup
pthread_attr_destroy(&attr);

这篇关于使用 pthreads 在挂起模式下创建线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆