C++ Condition Variable

Sharing the code which demonstrates synchronization between two threads. Two threads execute interchangeably, all thanks to the condition variable.

I have also shared the code execution output  

Check out the Video:



#include <iostream>

#include <thread>

#include <mutex>

#include <condition_variable>


using namespace std;


mutex m;

condition_variable cnd;

int previousThreadId;


void print(int threadID)

{

for (size_t i = 0; i < 20; i++)

{

unique_lock<std::mutex> ul(m);

//->Threads Waiting Zone

cnd.wait(ul, [&]()->bool {   

if (threadID != previousThreadId)

return true;

else

return false;

});

previousThreadId = threadID;

cout << "\nThread # " << threadID << " Executing...";

cout << "\nPrinting  : " << i<< "\n";

ul.unlock();

cnd.notify_one();

}

}




int main()

{

thread t[2];

for (size_t i = 0; i < 2; i++)

{

t[i] = thread(print, i);

}


for (size_t i = 0; i < 2; i++)

{

t[i].join();

}

return 0;

}

Output:



Comments

Popular posts from this blog

Step By Step Guide to Detect Heap Corruption in Windows Easily

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

How to dynamically add Properties in C# .NET?