pthread 条件变量 [英] pthread conditional variable

查看:69
本文介绍了pthread 条件变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个带有任务队列的线程.一旦第一个任务被添加到队列中,线程就会开始运行它.

I'm implementing a thread with a queue of tasks. As soon as as the first task is added to the queue the thread starts running it.

应该使用pthread条件变量来唤醒线程还是有更合适的机制?

Should I use pthread condition variable to wake up the thread or there is more appropriate mechanism?

如果我在另一个线程没有被 pthread_cond_wait() 阻塞而是在做某事时调用 pthread_cond_signal(),会发生什么?信号会丢失吗?

If I call pthread_cond_signal() when the other thread is not blocked by pthread_cond_wait() but rather doing something, what happens? Will the signal be lost?

推荐答案

来自 pthread_cond_signal 手册:

如果当前没有线程阻塞在 cond 上,pthread_cond_broadcast() 和 pthread_cond_signal() 函数将不起作用.

The pthread_cond_broadcast() and pthread_cond_signal() functions shall have no effect if there are no threads currently blocked on cond.

我建议你使用信号量.基本上,每次将任务插入队列时,您都会向上"信号量.工作线程通过关闭"它来阻塞信号量.由于它将为每个任务启动"一次,因此只要队列中有任务,工作线程就会继续运行.当队列为空时,信号量为 0,工作线程会阻塞,直到新任务到达.信号量也很容易处理当工作人员忙时有超过 1 个任务到达的情况.请注意,您仍然必须锁定对队列的访问以保持插入/删除原子性.

I suggest you use Semaphores. Basically, each time a task is inserted in the queue, you "up" the semaphore. The worker thread blocks on the semaphore by "down"'ing it. Since it will be "up"'ed one time for each task, the worker thread will go on as long as there are tasks in the queue. When the queue is empty the semaphore is at 0, and the worker thread blocks until a new task arrives. Semaphores also easily handle the case when more than 1 task arrived while the worker was busy. Notice that you still have to lock access to the queue to keep inserts/removes atomic.

这篇关于pthread 条件变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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