DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

thread synchronization c++

Create 2 thread and print ping and pong multiple time.

Source code of multi threading c++:

/*
Program: Two thread synchronization 
Author: Alpha Master
Date: 24 sep 2021
*/

//Header File
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>

std::mutex mtx;
std::condition_variable cv;
bool ready = true;
bool processed = false;

void funOne()
{
    auto i{0};
    while(i<5)
    {
    	// Wait
    	std::unique_lock<std::mutex> lk(mtx);
    	cv.wait(lk, []{return ready;});
        
        //print
       	std::cout<<"ping"<<std::endl;
	    ++i;
        
        //send
        ready = false;
        processed = true;
        lk.unlock();
        cv.notify_one();
    }

}

void funTwo()
{
    auto i{0};
    while(i<5)
    {
        // Wait
        std::unique_lock<std::mutex> lk(mtx);
        cv.wait(lk, []{return processed;});
 
        //print
    	std::cout<<"pong"<<std::endl;
  	    ++i;

        //send
        processed = false;
        ready= true;
        lk.unlock();
        cv.notify_one();

    }

}

int main()
{
    std::cout<<"Two thread synchronization"<<std::endl;

    std::thread th1(funOne);
    std::thread th2(funTwo);
    th1.join();
    th2.join();

    return 0;
}

Output:

Two thread synchronization
ping
pong
ping
pong
ping
pong
ping
pong
ping
pong

Primary Sidebar

DigestCPP © 2022. All rights reserved from 2019.

    Contact Us   Disclaimer