It was only today that C++11 supported atomic operations and also supported the thread class to create threads, which is really getting 6. Before doing the project, the creation thread is the POSIX standard pthread_create function, and the thread synchronization is generally used Pthread_mutex. Today get a new skill, you can use the thread class to create a thread, with the Atomic_flag implementation of spin lock for thread synchronization, do not say, and quickly take the small notebook to write down:
1#include <iostream>2#include <vector>3#include <thread>4#include <atomic>5 using namespacestd;6 Longn=0;7Std::atomic_flagLock=Atomic_flag_init;8 voidThreadfun (intn)//Thread entry function9 {Ten for(intI=0; i<10000000; ++i) One { A while(Lock. Test_and_set ());//Spin lock -++N; - Lock. Clear (); the } - } - intMain () - { +Vector<thread>Threadarray; - intthreadnum=2; +cout<<"I am Main thread, n="<<N<<Endl; A for(intI=0; i<threadnum; ++i)//create thread at { - Threadarray.emplace_back (Threadfun, i); - } - for(intI=0; I<threadarray.size (); ++i)//recycle thread - { - Threadarray[i].join (); in } -cout<<"I am Main thread, n="<<N<<Endl; to return 0; +}
C++11 new features atomic and thread