Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Trying out `conditional_variable` in threads (C++)
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <string>
#include <chrono>
#include <vector>
int nWorkersActive;
std::mutex mtxAccess;
std::condition_variable cvCond;
std::vector<std::thread> vecWorkers;
void worker(std::string strMessage) {
std::unique_lock<std::mutex> ulLock(mtxAccess);
nWorkersActive++;
cvCond.wait_for(ulLock, std::chrono::milliseconds(100));
std::cout << strMessage << std::endl;
nWorkersActive--;
}
void addWorker(std::string strMessage) {
vecWorkers.push_back(std::thread(worker, strMessage));
}
void joinWorkers() {
for(std::thread& thrWorker : vecWorkers) {
thrWorker.join();
}
}
int main() {
nWorkersActive = 0;
addWorker("Thread 1");
addWorker("Thread 2");
addWorker("Thread 3");
while(nWorkersActive > 0) {
cvCond.notify_one();
}
joinWorkers();
return 0;
}
@fairlight1337

This comment has been minimized.

Copy link
Owner Author

@fairlight1337 fairlight1337 commented Apr 24, 2016

Compile this with

$ g++ Conditional.cpp -std=c++11 -pthread

The worker's messages are printed one at a time, depending on the order in which the threads receive the notify_one call on the condition_variable cvCond.

Its also possible to use detach() after creating each thread instead of using joinWorkers in the end. But then it might happen that the main function returns (and thus, the program ends) before any of the threads had time to act. In this case, the main thread effectively went first of all threads in the program.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment