mutex

A mutex is a synchronization primitive. Mutexes provide lock and unlock functions which exclude other threads from entering protected sections of code.

Only the locking thread can advance passed a call to lock() : other threads will block there until the locking thread calls unlock().

#include <vector>
#include <iostream>

#include <thread>
#include <mutex>

::std::vector
   <
   unsigned
   >
   data;

::std::mutex
   mutex;

void load_data(unsigned value)
{
   //
   // Sleep briefly, then upload a value to 'data':
   //
   
   ::std::this_thread::sleep_for 
      (
      ::std::chrono::seconds(1)
      )
      ;
   
   //
   // Lock the mutex:
   //
   
   mutex.lock();
   
   data.push_back
      (
      value
      )
      ;
   
   //
   // Release the mutex:
   //
   
   mutex.unlock();
   
   return;
}

int main(int argc, char ** argv)
{
   ::std::vector
      <
      ::std::thread
      >
      threads;
   
   //
   // Start 10 threads, each with a different value to
   // insert into 'data':
   //
   
   for(unsigned i = 0; i< 10; ++i)
   {
      threads.push_back
         (
         ::std::thread( load_data, i )
         )
         ;
   }
   
   for(unsigned i = 0; i< 10; ++i)
   {
      threads[i].join();
   }
   
   //
   // Display the contents of 'data':
   //
   
   for( auto const & datum : data )
   {
      ::std::cout << datum << " ";
   }
   ::std::cout << ::std::endl;
   
   return 0;
}

Possible output:

0 1 3 5 4 6 9 2 7 8

Note that, in general, the data was not inserted in the order 0 1 2 3 4 5 6 7 8 9. This is because the threads competed to acquire a mutex lock, and the order in which the threads were successful is only known at runtime.