c++ - How can let a C++11 thread run several different functions? -
i learning new multi-threading techniques in c++11. tutorials read on web teaching how launch new thread(or several threads) executing function, how join (or detach) thread(or threads) later , how avoid racing conditions using mutex
, etc.
but don't see of them showing how make thread execute several functions @ different parts of program. question is, c++11 threads, possible achieve following? if so, how? (giving example great).
void func1(std::vector<int> & data1){ ... } void func2(std::vector<int> & data2){ ... } // main function version int main(){ std::vector<int> data1; // prepare data1 func1; std::thread t1(func1, std::ref(data1)); std::vector<int> data2; // prepare data2 func2; if (func1 in t1 done){ t1(func2, std::ref(data2)); } t1.join(); return 0; }
and further, if want put the above main
function body loop, following. possible? if so, how?
//main function version ii int main(){ std::vector<int> bigdata1; std::vector<int> bigdata2; std::thread t1; // can without telling t1 function // executed? for(int i=0; i<10; ++i){ // main thread prepare small chunk smalldata1 bigdata1 func1; if(t1 ready execute function){t1(func1, std::ref(smalldata1));} // main thread other stuff, , prepare small chunk smalldata2 bigdata2 func2; if (func1 in t1 done){ t1(func2, std::ref(smalldata2)); } } t1.join(); return 0; }
reference cplusplus.com:
default constructor constructs thread object not represent thread of execution.
therefore std::thread t
doesn't define executable thread. thread function has provided when creating thread , cannot set afterwards.
for main function version i, have create 2 threads. following:
int main(){ std::vector<int> data1; // prepare data1 func1; std::thread t1(func1, std::ref(data1)); std::vector<int> data2; // prepare data2 func2; t1.join(); // how wait till func1 done // have create new thread here func2 std::thread t2(func2, std::ref(data2)); t2.join(); // wait thread2 (func2) end return 0; }
similarly, can put them in loop , alright give main function version ii.
Comments
Post a Comment