C++11 Concurrency Features

    Concept        Header     Summary 
    Threads   <thread>  Standard, low-level, type-safe;
    Futures   <future> Via async function, hides threading;
    Locks   <mutex> Standard, low-level locking primitives
    Condition Vars   <condition_variable>  Low-level synchronization primitives
    Atomics   <atomic> Predictable, concurrent access without data race
  • How to avoid data races
  1.     redesign to eliminate sharing data
  2.     use thread-safe entities(e.g. parallel collections)
  3.     use synchronization(e.g. lock atom...)
  • Using RAII( Resource Acquisition Is Initialization ) to avoid data races

   old style

#include <mutex>

#include <thread>



std::mutex m;

int sum = 0;



std::thread t1( [&] () {

    int r = func();

    m.lock();

    sum += r;

    m.unlock();

});

 using RAII

std::mutex m;

int sum = 0;



std::thread t1( [&] () {

    int r = func();

    {

        lock_guard<mutex> locker(m);

        sum += r;

    }

});

 

你可能感兴趣的:(concurrency)