Monday, 2 March 2015

C++11 Threads

C++11 has introduced std::thread. The important thing to note about this class is that, it does not have copy constructor and copy assignment, but has move constructor and move assignment operator.

Below is the simple example I found
 #include <iostream>  
 #include <thread>  
 #include <vector>  
 #include <atomic>  
   
 std::atomic<bool> ready(false);  
 std::atomic_flag winner = ATOMIC_FLAG_INIT;  
   
 void count1m(int id) {  
      while (!ready)  
           std::this_thread::yield();  
   
      for (volatile int i = 0; i < 1000000; ++i) {  
           // just count;  
      }  
   
      if (!winner.test_and_set()) {  
           std::cout << "thread #" << id << "won!\n";  
      }  
 }  
   
 int main() {  
      std::vector<std::thread> threads;  
      std::cout << "spawning 10 threads that count to 1 million...\n";  
   
      for (int i = 1; i <= 10; ++i)  
           threads.push_back(std::thread(count1m, i));  
   
      ready = true;  
      for (std::thread& thread : threads)  
           thread.join();  
   
      getchar();  
 }  

No comments:

Post a Comment