Created
April 24, 2016 21:21
-
-
Save fairlight1337/09840901623b7e7c3d16a70f12b585d9 to your computer and use it in GitHub Desktop.
Trying out `conditional_variable` in threads (C++)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile this with
The worker's messages are printed one at a time, depending on the order in which the threads receive the
notify_one
call on thecondition_variable
cvCond
.Its also possible to use
detach()
after creating each thread instead of usingjoinWorkers
in the end. But then it might happen that themain
function returns (and thus, the program ends) before any of the threads had time to act. In this case, themain
thread effectively went first of all threads in the program.