C++

C++ : Sequential Thread Execution Using Condition Variables

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

std::condition_variable cond;
std::mutex mu;
int current = 0;
bool ready = false;

// Execute the threads only in the sequential order ( i.e based on the id passed to it)
void PrintId (int id) {

    std::unique_lock <std::mutex> locker(mu);
    // Thread(s) would wake up upon receiving a notification by [notify.all()] call.
    // Will come out of while loop only if the current matches with id passed to the running 
    // thread. If it doesn't match, it will go back to sleep.
    while (!ready || current != id) { 
        cond.wait(locker);
    }
    
    std::cout << "===== Thread id : " << id << std::endl;
    current++;
    cond.notify_all();
}

int main() {

    std::thread threads[15];
    for (int i=0; i<15; i++) {
        threads[i] = std::thread(PrintId, i);
    }

    ready = true;
    cond.notify_all();
    
    for (auto& th : threads) 
        th.join();

    return 0;
}

Output

$ ./a.out 
===== Thread id : 0
===== Thread id : 1
===== Thread id : 2
===== Thread id : 3
===== Thread id : 4
===== Thread id : 5
===== Thread id : 6
===== Thread id : 7
===== Thread id : 8
===== Thread id : 9
===== Thread id : 10
===== Thread id : 11
===== Thread id : 12
===== Thread id : 13
===== Thread id : 14


Copyright (c) 2019-2022, Algotree.org.
All rights reserved.