Skip to content

Commit 2e21da0

Browse files
authored
Update producer_consumer1.cpp
I thought this might make a good testbed for reporting a problem with debugging threads in an IDE. The print() function with mutex makes it print cleanly.
1 parent 7a2bc2a commit 2e21da0

File tree

1 file changed

+31
-16
lines changed

1 file changed

+31
-16
lines changed

Concurrency/Queue/producer_consumer1.cpp

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,34 @@
66

77
#include "Queue.h"
88
#include <iostream>
9+
#include <sstream>
10+
11+
const int nbConsumers = 4;
12+
const int nbToConsume = 3;
13+
const int nbToProduce = nbToConsume * nbConsumers;
14+
15+
void print(std::string x) {
16+
static std::mutex mutex;
17+
std::unique_lock<std::mutex> locker(mutex);
18+
std::cout << x << "\n";
19+
}
20+
921

1022
void produce(Queue<int>& q) {
11-
for (int i = 0; i< 10000; ++i) {
12-
std::cout << "Pushing " << i << "\n";
23+
for (int i = 1; i <= nbToProduce; ++i) {
24+
std::ostringstream tmp;
25+
tmp << "--> " << i;
26+
print(tmp.str());
1327
q.push(i);
1428
}
1529
}
1630

1731
void consume(Queue<int>& q, unsigned int id) {
18-
for (int i = 0; i< 2500; ++i) {
32+
for (int i = 0; i < nbToConsume; ++i) {
1933
auto item = q.pop();
20-
std::cout << "Consumer " << id << " popped " << item << "\n";
34+
std::ostringstream tmp;
35+
tmp << " " << item << " --> C" << id;
36+
print(tmp.str());
2137
}
2238
}
2339

@@ -26,21 +42,20 @@ int main()
2642
{
2743
Queue<int> q;
2844

29-
using namespace std::placeholders;
30-
31-
// producer thread
45+
// Start the producer thread.
3246
std::thread prod1(std::bind(produce, std::ref(q)));
3347

34-
// consumer threads
35-
std::thread consumer1(std::bind(&consume, std::ref(q), 1));
36-
std::thread consumer2(std::bind(&consume, std::ref(q), 2));
37-
std::thread consumer3(std::bind(&consume, std::ref(q), 3));
38-
std::thread consumer4(std::bind(&consume, std::ref(q), 4));
48+
// Start the consumer threads.
49+
std::vector<std::thread> consumers;
50+
for (int i = 0 ; i < nbConsumers ; ++i) {
51+
std::thread consumer(std::bind(&consume, std::ref(q), i + 1));
52+
consumers.push_back(std::move(consumer));
53+
}
3954

4055
prod1.join();
41-
consumer1.join();
42-
consumer2.join();
43-
consumer3.join();
44-
consumer4.join();
56+
57+
for (auto& consumer : consumers) {
58+
consumer.join();
59+
}
4560

4661
}

0 commit comments

Comments
 (0)