简体   繁体   English

如何在C ++中实现阻塞队列以处理线程之间的数据?

[英]How to implement a blocking queue in C++ to process data between threads?

I need to make an app that will have two threads. 我需要制作一个具有两个线程的应用程序。 One will produce data (file paths and an action to be performed for that path - create/update/delete) and the other thread will need to consume this data and actually perform the tasks. 一个将产生数据(文件路径和对该路径要执行的操作-创建/更新/删除),而另一个线程将需要使用此数据并实际执行任务。

For this I thought to have a queue and from one thread to put data in it and from the other to take the items and performa the actions sequentially. 为此,我认为要有一个队列,从一个线程将数据放入队列,从另一个线程取数据并按顺序执行操作。

My problem is how do I make this data to be shareable between these threads and then how can I make the second thread to block while waiting for data to be put in the queue? 我的问题是如何使这些线程之间的数据可共享,然后如何在等待数据放入队列时使第二个线程阻塞? Just having a while to check if queue is not empty would eat CPU like crazy for nothing. 仅仅有一段时间检查队列是否不为空,会像疯了一样吞噬CPU。 Adding a "sleep" to check every few milliseconds or seconds would not be efficient. 每隔几毫秒或几秒钟添加一次“睡眠”检查将没有效率。

How can this be done? 如何才能做到这一点? Any libraries that implement such data? 有没有实现此类数据的库?

A couple of examples for you: 为您提供一些示例:

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

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