pthread线程池场景
我想使用 pthread 实现以下场景: 线程池中有两种线程。第一种执行(比如说)fun1,第二种执行fun2。主线程启动这两个线程(为简单起见,假设池中只有两个工作线程,分别是上述两种不同类型的线程)。然后主线程等待其中一个线程完成。第一个完成的线程通知主线程,然后主线程应该通知另一个工作线程停止执行其作业。如此循环下去。
现在,如果我想阻止一个线程执行其作业(例如 memmove/lock acquire ),那么我认为最好只是终止/取消该线程并重新创建它。你们觉得怎么样?
另外,如果我取消线程(pthread_cancel),那么我似乎必须调用 pthread_join 以确保它实际上被取消,然后重新创建它。这是真的吗?
谢谢, 尼勒什。
I want to achieve following kind of scenario using pthreads:
There are two kinds of threads in a thread pool. First kind executes (say) fun1 second executes fun2. The main thread starts these two threads (for simplicity assume that there are only two worker threads in the pool each of the above two different kinds). The main thread then waits for one of the threads to finish. The first thread to finish notifies the main thread, the main thread then should notify the other worker thread to quit executing its job. And the cycle goes on.
Now if I wanted to stop a thread from executing its job, which can be like memmove/lock acquire, then I think it's best to just kill/cancel that thread and recreate it. What do you guys think?
Also if I cancel the thread (pthread_cancel) then it seems like I will have to call pthread_join to ensure it's actually canceled and then recreate it. Is that true?
Thanks,
Nilesh.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不存在用 pthreads 杀死线程这样的事情。正如您所发现的,存在取消,但是否对取消起作用取决于线程。仅当 (1) 尚未使用 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE); 阻止线程并且 (2) 线程调用作为取消点的函数时,才会执行取消操作。
您还需要使用某种同步操作来确保取消已被执行,这是正确的。一种方法是在线程上调用
pthread_join
,但是如果程序中的另一个点可能已经在其上调用pthread_join
(调用pthread_join
两次调用 UB!)。在这种情况下,您可以安装一个取消清理处理程序,该处理程序在运行时发布到信号量或发出条件变量信号,并以这种方式等待通知。There is no such thing as killing a thread with pthreads. As you've found, there's cancellation, but it's up to the thread whether it acts on cancellation. Cancellation will only be acted upon if (1) it hasn't been blocked with
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE);
and (2) the thread calls a function which is a cancellation point.You're also right about needing to use some sort of synchronization operation to ensure the cancellation has been acted upon. One way to do this would be calling
pthread_join
on the thread, but that could be problematic if another point in your program might already be callingpthread_join
on it (callingpthread_join
twice invokes UB!). In this case you could install a cancellation cleanup handler that posts to a semaphore or signals a condition variable when it runs, and wait for the notification that way.