Skip to content

techtrendings.com

Let's explore

Menu
Menu

Print Odd Even in Separate threads in C++| TechTrendings

Posted on May 24, 2022May 24, 2022 by Avidlearner

This is a popular question asked for experience programmer while testing multithreading knowledge. We can do it in two ways.

Approach 1: Using lock mechanism

#include<iostream>
#include<thread>
#include<mutex>

using namespace std;

std::mutex m;
int count = 0;

void printEven()
{
    cout<< "Entered Even\n"<<endl;
    while(count <= 10)
    {
       m.lock();
       if(count%2 == 0)
           cout<< count++ << "";
       m.unlock();
     }
}

void printOdd()
{
    cout<< "Entered odd\n"<<endl;
    while(count < 10)
    {
       m.lock();
       if(count%2 == 1)
           cout<< count++ << "";
       m.unlock();
     }
}

int main()
{
    std::thread t1(printOdd);
    std::thread t2(printEven);
    t1.join();
    t2.join();
    return 0;
}

Approach 2: Using Condition variable

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mu;
std::condition_variable cond;
int count = 1;

void PrintOdd()
{
    for(; count < 10;)
    {
        std::unique_lock<std::mutex> locker(mu);
        cond.wait(locker,[](){ return (count%2 == 1); });
        std::cout << "From Odd:    " << count << std::endl;
        count++;
        locker.unlock();
        cond.notify_all();
    }

}

void PrintEven()
{
    for(; count < 10;)
    {
        std::unique_lock<std::mutex> locker(mu);
        cond.wait(locker,[](){ return (count%2 == 0); });
        std::cout << "From Even: " << count << std::endl;
        count++;
        locker.unlock();
        cond.notify_all();
    }
}

int main()
{
    std::thread t1(PrintOdd);
    std::thread t2(PrintEven);
    t1.join();
    t2.join();
    return 0;
}

Related

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Implement Trie Data Structure in C++- LeetCode
  • How TLS Works
  • C++ – Factory Design Pattern – Creation Design Pattern
  • C++ – Strategy Design Pattern – Behavioral Design Pattern
  • LFU Cache Implementation – LeetCode

Recent Comments

  • automatically like friends photos on instagram on Program to find unpaired element in an Array in C++|Leetcode |techtrendings
  • Twicsy on Program to find unpaired element in an Array in C++|Leetcode |techtrendings

Archives

  • January 2023
  • November 2022
  • August 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022

Categories

  • Algorithm
  • Algorithm
  • C++
  • Design Patterns
  • Multithreading
  • OS Concepts
  • Programming
  • Uncategorized

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Join Our Mailing List for the Latest News and Updates.

© 2023 techtrendings.com | Powered by Superbs Personal Blog theme