当 pthreads 在 mutex_lock/cond_wait 中等待时会发生什么?
我有一个程序可以最大限度地利用我的CPU。
它是通过 pthreads 实现多线程的,除了它们“仅”让我的核心达到大约 60% 的负载这一事实之外,它还可以很好地完成它们的工作,在我看来,这还不够。
我正在寻找原因,并问自己(并在此问你)阻塞函数 mutex_lock/cond_wait 是否是候选者?
当线程无法在这样的函数中运行时会发生什么?
- pthread 是否切换到它处理的另一个线程,或者
- 该线程是否将其时间交给系统,如果是后者,我可以更改此行为吗?
问候,
没有人
更多信息 该设置是一个填充任务池的主线程,以及无数从那里获取作业的工作线程,并在完成序列化计算时等待通过广播发出的条件信号。他们继续计算此计算中的值,直到完成,交付邮件并获取下一个工作......
I have a program that should get the maximum out of my cpu.
It is multithreaded via pthreads that do their job well apart from the fact that they "only" get my cores to about 60% load which is not enough in my opinion.
I am searching for the reason and am asking myself (and hereby you) if the blocking functions mutex_lock/cond_wait are candidates?
What happens when a thread cannot run on in such a function?
- Does pthread switch to another thread it handles or
- does the thread yield its time to the system and if the latter is the case, can I change this behavior?
Regards,
Nobody
More Information
The setting is one mainthread that fills the taskpool and countless workers that fetch jobs from there and wait on a conditional that is signaled via broadcast when a serialized calculation is done. They go on with the values from this calculation until they are done, deliver their mail and fetch the next job...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在典型的现代 pthreads 实现中,每个线程都由内核管理,与单独的进程没有什么不同。任何阻塞调用,如 pthread_mutex_lock 或 pthread_cond_wait (还有,例如,read),都会将其时间交给系统。然后系统会找到另一个符合条件的线程来调度,无论是在您的进程还是其他进程中,并运行它。
如果您的程序仅占用 60% 的 CPU,则它更有可能在 I/O 上阻塞,而不是在 pthread 操作上阻塞,除非您对 pthread 操作做了过于精细的操作。
On a typical modern pthreads implementation, each thread is managed by the kernel not unlike a separate process. Any blocking call like
pthread_mutex_lock
orpthread_cond_wait
(but also, say,read
) will yield its time to the system. The system will then find another eligible thread to schedule, whether in your process or another process, and run it.If your program is only taking 60% of the CPU, it is more likely blocked on I/O than on pthread operations, unless you have done something way too granular with your pthread operations.
如果线程正在等待互斥体/条件,则它不会使用资源(好吧,仅使用少量资源)。每当线程进入等待状态时,控制权就会切换到其他线程。当互斥体被释放(或条件变量发出信号)时,线程被唤醒并可能获取互斥体(如果没有其他线程首先获取它),并继续运行。然而,如果其他线程获取互斥体(如果有多个线程正在等待它,则可能会发生这种情况),则该线程将返回睡眠状态。
If a thread is waiting on a mutex/condition, it doesn't use resources (well, uses just a tiny amount). Whenever the thread enters waiting state, control switches to other threads. When the mutex is released (or condition variable signalled), the thread wakes up and may acquire the mutex (if no other thread grabs it first), and continue to run. If however some other thread acquires the mutex (this can happen if several threads are waiting for it), the thread returns to sleeping state.