I am learning the new multi-threading techniques in C++11. Almost all the tutorials I read on the web is teaching how to launch a new thread(or several threads) executing a function, how to join (or detach) the thread(or threads) later and how to avoid racing conditions using mutex, etc.
But I don't see any of them showing how to make a thread execute several functions at different parts of the program. The question is, with C++11 threads, is it possible to achieve the following? If so, how? (Giving an example will be great).
void func1(std::vector<int> & data1){ ... } void func2(std::vector<int> & data2){ ... } // main function version I int main(){ std::vector<int> data1; // prepare data1 for func1; std::thread t1(func1, std::ref(data1)); std::vector<int> data2; // prepare data2 for func2; if (func1 in t1 is done){ t1(func2, std::ref(data2)); } t1.join(); return 0; } And further, what if I want to put the the above main function body into a loop, as following. Is it possible? If so, how?
//main function version II int main(){ std::vector<int> bigdata1; std::vector<int> bigdata2; std::thread t1; // Can I do this without telling t1 the function // to be executed? for(int i=0; i<10; ++i){ // main thread prepare small chunk smalldata1 from bigdata1 for func1; if(t1 is ready to execute a function){t1(func1, std::ref(smalldata1));} // main thread do other stuff, and prepare small chunk smalldata2 from bigdata2 for func2; if (func1 in t1 is done){ t1(func2, std::ref(smalldata2)); } } t1.join(); return 0; }
std::condition_variableto make the second thread wait for the first one. Also, if you can get your hands on this book you'll probably learn a lot from the person who implemented most of thestd::thread.std::atomicvariable maintains state that main can mess with. Check state, do task, repeat... If the task's not done yet, no state check and no progressing into the next task. If the next task's not ready, park in an idle state that's basically a short sleep.