Skip to content

techtrendings.com

Let's explore

Menu
Menu

Print Odd and Even in Separate thread – C++ Multithreading

Posted on January 14, 2022January 14, 2022 by Avidlearner

In this article we will discuss about the how to print odd and even number in separate threads. Let’s see

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

using namespace std;

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" << 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;
}

We can also use condition and notify with threads to print odd and even in separate threads.

#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