#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
const int N = 15; // Change N to print up to any number
int current = 1; // Shared variable to track the number to print
mutex mtx; // Mutex for synchronization
condition_variable cv; // Condition variable for coordination
void printNumber(int thread_id) {
while (true) {
unique_lock<mutex> lock(mtx);
// Wait until it's this thread's turn
cv.wait(lock, [thread_id]() { return (current % 3 == thread_id); });
// If all numbers are printed, exit
if (current > N) {
cv.notify_all();
return;
}
// Print the current number
cout << "Thread " << thread_id << ": " << current << endl;
current++; // Increment to next number
lock.unlock();
// Notify all threads that a new number is available
cv.notify_all();
}
}
int main() {
thread t1(printNumber, 0);
thread t2(printNumber, 1);
thread t3(printNumber, 2);
t1.join();
t2.join();
t3.join();
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: