#include<iostream>#include<utility>#include<thread>#include<chrono>voidf1(intn){for(inti=0;i<5;++i){std::cout<<"Thread 1 executing\n";++n;std::this_thread::sleep_for(std::chrono::milliseconds(10));}}voidf2(int&n){for(inti=0;i<5;++i){std::cout<<"Thread 2 executing\n";++n;std::this_thread::sleep_for(std::chrono::milliseconds(10));}}classfoo{public:voidbar(){for(inti=0;i<5;++i){std::cout<<"Thread 3 executing\n";++n;std::this_thread::sleep_for(std::chrono::milliseconds(10));}}intn=0;};classbaz{public:voidoperator()(){for(inti=0;i<5;++i){std::cout<<"Thread 4 executing\n";++n;std::this_thread::sleep_for(std::chrono::milliseconds(10));}}intn=0;};intmain(){intn=0;foof;bazb;std::threadt1;// t1 is not a thread
std::threadt2(f1,n+1);// pass by value
std::threadt3(f2,std::ref(n));// pass by reference
std::threadt4(std::move(t3));// t4 is now running f2(). t3 is no longer a thread
std::threadt5(&foo::bar,&f);// t5 runs foo::bar() on object f
std::threadt6(b);// t6 runs baz::operator() on a copy of object b
t2.join();t4.join();t5.join();t6.join();std::cout<<"Final value of n is "<<n<<'\n';std::cout<<"Final value of f.n (foo::n) is "<<f.n<<'\n';std::cout<<"Final value of b.n (baz::n) is "<<b.n<<'\n';}
#include<iostream>#include<thread>#include<chrono>voidfoo(){// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));}voidbar(){// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));}intmain(){std::cout<<"starting first helper...\n";std::threadhelper1(foo);std::cout<<"starting second helper...\n";std::threadhelper2(bar);std::cout<<"waiting for helpers to finish..."<<std::endl;helper1.join();helper2.join();std::cout<<"done!\n";}
Output:
1
2
3
4
starting first helper...
starting second helper...
waiting for helpers to finish...
done!