简体   繁体   English

具有多个使用者的线程队列

[英]Thread queue with multiple consumer

I'm doing threaded queue with consumer getting items from queue and producer put items into queue. 我正在与消费者从队列中获取项目的线程进行队列,而生产者将项目放入队列。 The number of consumer created is from user input. 创建的消费者数量来自用户输入。 I tried following two ways. 我尝试了以下两种方法。 First version works well but the second is not. 第一个版本运作良好,但第二个版本则无效。 I cannot use first version because of user input constraint. 由于用户输入限制,我无法使用第一个版本。 Actually I didn't get the difference between the two. 其实我没有得到两者之间的区别。 Is the first one creating three threads at the same time while second one create one by one? 第一个同时创建三个线程,而第二个则一个一个地创建吗? Any clue on this? 有什么线索吗?

auto c1 = async(launch::async, consumer);
auto c2 = async(launch::async, consumer);
auto c3 = async(launch::async, consumer);

for(int i = 1; i <= 3; i++)
    auto c1 = async(launch::async, consumer);

Both are, in a way, equal, as both starts three asynchronous tasks one after another. 两者在某种意义上是相等的,因为它们一个接一个地启动三个异步任务。

Both are, in a way, different, as for the loop the variable c1 is confined to a lifetime inside the loop and will go out of scope (and be destructed) every time the loop iterates. 两者在某种程度上是不同的,因为对于循环,变量c1限于循环内的生存期,并且每次循环迭代时,变量c1都会超出范围(并被破坏)。 And it's probably this that makes all the difference: The object c1 is destructed and have to wait for the consumer function to finish before it can be destructed. 可能正是这与众不同:对象c1被销毁,必须等待consumer函数完成后才能销毁。

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

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