multithreading - C++ thread get value for each loop -


i start learn c++, , i'm playing multithreading. trying current value in loop.

like :

std::atomic_int res(0); void testthread(void){   for(int = 0; < 5; i++)     res += i; }  int main(void){   std::thread t(testthread);   for(int = 0; < 5; i++){     std::cerr << "res : " << res << std::endl;   }   t.join();   return 0; } 

i know wrong don't know how fix it... tried find how it, didn't find want.

nothing wrong code. thread function finishes quickly. here's example sleep_for():

atomic_int res = 0; thread t([&] {     (int = 0; < 5; ++i)     {         this_thread::sleep_for(chrono::seconds(1));         res += i;     } });  (int = 0; < 20; ++i) {     this_thread::sleep_for(chrono::milliseconds(400));     cout << "res : " << res << endl; }  t.join(); 

by way, switched lambda expression no global variable , global function needed.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -