fbpx ...

Multithreading – Data sharing

The role of this training is to show common pitfalls and good practices on using data sharing in C++17. There are practical exercises with fixing undefined behaviour caused by misuse of multithreading concepts.

We will analyse such code

  #include <vector>
#include <thread>
#include <chrono>
#include <iostream>
#include <mutex>

using namespace std;

void do_work(ind id, mutex & m) {
    this_thread::sleep_for(100ms);
    lock_guard<mutex> lock(m);
    cout << "Thread [" << id << "]: "
         << "Job done!" << endl;
}

int main() {
    mutex m;
    vector<thread> threads;
    for (int i = 0; i < 20; i++) {
        threads.emplace_back(thread(do_work, i, ref(m)));
    }
    for (auto && t : threads) {
        t.join();
    }
    return 0;
}  
  #include <thread>
#include <mutex>
using namespace std;

class X {
    mutable mutex mtx_;
    int value_ = 0;
public:
    explicit X(int v) : value_(v) {}

    bool operator<(const X & other) const {
        lock_guard<mutex> ownGuard(mtx_);
        lock_guard<mutex> otherGuard(other.mtx_);
        return value_ < other.value_;
    }
};

int main() {
    X x1(5);
    X x2(6);
    thread t1([&](){ x1 < x2; });
    thread t2([&](){ x2 < x1; });
    t1.join();
    t2.join();
    return 0;
}  

Your abilities after Multithreading – Data sharing training

Agenda

Activities

Duration

Form

Order Multithreading – Data sharing training

Related trainings

Performance optimizations

Information about false sharing

Multithreading - threads

Basic building block of concurrent programs

Multithreading - asynchronous tasks

Higher level multithreading mechanisms

Multithreading - atomic, conditional_variable, call_once

other utilities from thread support library that are used with threads or asynchronous tasks
ninjaletter

Już uciekasz?

Zanim to zrobisz, zapisz się na Ninjaletter, aby wiedzieć, co piszczy w C++. 

Informujemy, iż w celu realizacji usług dostępnych w naszym serwisie, optymalizacji jej treści, dostosowania strony do Państwa indywidualnych potrzeb oraz wyświetlania, personalizacji i mierzenia skuteczności reklam w ramach zewnętrznych sieci reklamowych korzystamy z informacji zapisanych za pomocą plików cookies na urządzeniach końcowych użytkowników. Pliki cookies można kontrolować za pomocą ustawień swojej przeglądarki internetowej. Dalsze korzystanie z naszego serwisu, bez zmiany ustawień przeglądarki internetowej oznacza, iż użytkownik akceptuje stosowanie plików cookies. Więcej informacji zawartych jest w polityce prywatności serwisu.