Repository navigation
Expand file tree
/
Copy pathexpno 10.cpp
More file actions
66 lines (62 loc) · 1.47 KB
/
Copy pathexpno 10.cpp
File metadata and controls
66 lines (62 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <atomic>
#include <chrono>
using namespace std;
queue<int> buffer;
mutex mtx;
condition_variable cv;
const int MAX_ITEMS = 10;
atomic<int> producedCount(0);
atomic<bool> finished(false);
// Producer function
void producer()
{
for (int i = 1; i <= MAX_ITEMS; i++)
{
this_thread::sleep_for(
chrono::milliseconds(100));
{
lock_guard<mutex> lock(mtx);
buffer.push(i);
producedCount++;
cout << "Produced: " << i << endl;
}
cv.notify_one();
}
finished = true;
cv.notify_all();
}
// Consumer function
void consumer()
{
while (true)
{
unique_lock<mutex> lock(mtx);
cv.wait(lock, []
{ return !buffer.empty() || finished; });
if (buffer.empty() && finished)
break;
int item = buffer.front();
buffer.pop();
lock.unlock();
cout << "Consumed: " << item << endl;
}
}
int main()
{
cout << "Producer-Consumer System Started\n"
<< endl;
thread producerThread(producer);
thread consumerThread(consumer);
producerThread.join();
consumerThread.join();
cout << "\nTotal Items Produced: "
<< producedCount << endl;
cout << "Producer-Consumer System Completed"
<< endl;
return 0;
}