Created
February 26, 2019 07:11
-
-
Save hmenn/1b71091a77eca15287447c9cb12512c2 to your computer and use it in GitHub Desktop.
basic thread example from modern cpp concurrency in depth
This file contains hidden or 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 <queue> | |
#include <thread> | |
#include <atomic> | |
#include <string> | |
#include <chrono> | |
int main() { | |
std::queue<int> qth1, qth2; | |
std::thread th1, th2; | |
std::atomic<bool> doneFlag{false}; | |
th1 = std::thread([&](){ | |
while(!doneFlag){ | |
if(qth1.empty()){ | |
std::this_thread::sleep_for(std::chrono::seconds(2)); | |
}else{ | |
int cmd = qth1.front(); | |
std::cerr<<"Thread1:"<<cmd<<std::endl; | |
qth1.pop(); | |
std::this_thread::sleep_for(std::chrono::seconds(2)); | |
} | |
} | |
}); | |
th2 = std::thread([&](){ | |
while(!doneFlag){ | |
if(qth2.empty()){ | |
std::this_thread::sleep_for(std::chrono::seconds(2)); | |
}else{ | |
int cmd = qth2.front(); | |
std::cerr<<"Thread2:"<<cmd<<std::endl; | |
qth2.pop(); | |
std::this_thread::sleep_for(std::chrono::seconds(2)); | |
} | |
} | |
}); | |
int cmd; | |
while(!doneFlag){ | |
std::cout<<"Enter command:"<<std::endl; | |
std::cin >> cmd; | |
if(cmd==0){ | |
qth1.push(cmd); | |
}else if(cmd==1){ | |
qth2.push(cmd); | |
}else if(cmd==2){ | |
doneFlag=true; | |
}else{ | |
std::cerr<<"Wrong Command."<<std::endl; | |
} | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
} | |
th1.join(); | |
th2.join(); | |
std::cout<<"All threads were joined. Program finished."<<std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment