Skip to content

Instantly share code, notes, and snippets.

@fairlight1337
Created April 24, 2016 21:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fairlight1337/09840901623b7e7c3d16a70f12b585d9 to your computer and use it in GitHub Desktop.
Save fairlight1337/09840901623b7e7c3d16a70f12b585d9 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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