Posts C++ quick exploration of threads
Post
Cancel

C++ quick exploration of threads

Synchronization primitives exist in C++ in the form of:

  • Atomic
  • Mutex
  • Semaphore
  • Memory fence
  • Transactional memory (might come in the future)

Considering the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <thread>

using namespace std;

int main() {
    int value = 42;

    auto t1 = thread{ [&value]{ ++value; } };
    auto t2 = thread{ [&value]{ value *= 2; } };
  
    t1.join();
    t2.join();

    cout << value << endl;
}

What are the possible outputs?

  • 43
  • 85
  • 84
  • 86
  • it is actually machine depended and not clearly defined

Lets now consider the same snippet using atomic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <atomic>
#include <iostream>
#include <thread>

using namespace std;

int main() {
    atomic_int value{42};

    auto t1 = thread{ [&value]{ ++value; } };
    auto t2 = thread{ [&value]{ value = value * 2; } };
  
    t1.join();
    t2.join();

    cout << value << endl;
}

What is the output now? A possibility of:

  • 84
  • 85
  • 86

What about using mutex?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main() {
    int value{42};
    mutex m;
    auto t1 = thread{ [&] {
        unique_lock block{m};
        ++value;
    } };
    auto t2 = thread{ [&] { 
        unique_lock block{m};
        value *= 2;
    } };
    t1.join(); t2.join();
    cout << value << endl;
}

What is the output now? A possibility of:

  • 85
  • 86
This post is licensed under CC BY 4.0 by the author.

Recent Update

    Contents