简体   繁体   English

C ++ pthread同步和多个线程唤醒

[英]C++ pthread synchronization and multiple wake up for thread

a question about C++ thread synchronization. 有关C ++线程同步的问题。 We suppose that have 2 pthreads: Thread1 and Thread2. 我们假设有2个pthread:Thread1和Thread2。

  • Thread1 is engaged in its task and, in some cases, he must notify the update of the state to the Thread2. 线程1从事其任务,在某些情况下,他必须将状态更新通知线程2。

  • Thread2 is engaged in its work of extracting data from a synchronized queue. Thread2从事从同步队列中提取数据的工作。 So, the Thread2 can sleep if the queue is empty. 因此,如果队列为空,则Thread2可以休眠。

How can I wake up the Thread2 on two conditions: 如何在两种情况下唤醒Thread2:

  • New message notification in the queue; 队列中有新消息通知;

    or 要么

  • status change of the Thread1 Thread1的状态更改

practical code-examples are welcome 欢迎提供实用的代码示例

For simplicity's sake, make Thread1 insert the status change notification as a task in the queue where it can be consumed by Thread2. 为简单起见,使Thread1将状态更改通知作为任务插入队列中,以便Thread2可以使用它。 If the notification has higher priority than regular work tasks, allow Thread1 to insert it in the queue ahead of other tasks, making it the next one to be consumed. 如果通知的优先级高于常规工作任务,请允许Thread1将其插入队列中的其他任务之前,使其成为下一个要使用的任务。

Why don't you also use the same queue(but different command code) to notify thread2? 为什么还不使用相同的队列(但命令代码不同)来通知thread2? Thread2 just waiting for any data in the queue in blocking mode, for each new message, check it's for status update or data, and do corresponding actions. Thread2仅以阻塞模式等待队列中的任何数据,对于每条新消息,检查其状态更新或数据,然后执行相应的操作。

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

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