Threads Sharing Data

Contents[Show]

One of the biggest challenges of thread management begins when the threads share non-const data

Data race and critical section

In threads using shared data, you often hear the expressions race condition and critical section. But what's that? 

Data Race
    A data race is a state, in which at least two threads access shared data at the same time, and at least one of the threads is a writer.
Critical Section
    A critical section is a section of the code, which not more than one thread should access at any point in time.

 

In case the program has a race condition, the program behavior is undefined. To say it differently, anything can happen.

A nice way to visualize a race condition is to let a few threads write to std::cout. std::cout is the shared object (output stream), that should be protected from simultaneous access by multiple threads.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// coutUnsynchronized.cpp

#include <chrono>
#include <iostream>
#include <thread>

class Worker{
public:
  Worker(std::string n):name(n){};
  
    void operator() (){
      for (int i= 1; i <= 3; ++i){
	// begin work
	std::this_thread::sleep_for(std::chrono::milliseconds(200));
	// end work
	std::cout << name << ": " << "Work " << i << " done !!!" << std::endl;
      }
      
    }
private:
  std::string name;
};


int main(){

  std::cout << std::endl;
  
  std::cout << "Boss: Let's start working.\n\n";
 
  std::thread herb= std::thread(Worker("Herb"));
  std::thread andrei= std::thread(Worker("  Andrei"));
  std::thread scott= std::thread(Worker("    Scott"));
  std::thread bjarne= std::thread(Worker("      Bjarne"));
  std::thread andrew= std::thread(Worker("        Andrew"));
  std::thread david= std::thread(Worker("          David"));
  
  herb.join();
  andrei.join();
  scott.join();
  bjarne.join();
  andrew.join();
  david.join();
  
  std::cout << "\n" << "Boss: Let's go home." << std::endl;
  
  std::cout << std::endl;

}

 

The boss assigns three work packages (lines 11 - 17) to each of its six workers (lines 32 - 36). When a worker is done with their work package it screams out loudly to the boss (line 16). When the boss has gotten notifications from all workers, it sends them home (line 45).

 What a mess!

 bossWorker

The same mess the next day. The workers scream out loudly. Totally unsynchronized.

bossWorker1

The first solution is a mutex. A mutex ensures, that each thread exclusively accesses the shared variable std::cout.

A side note: std::cout is thread-safe

The C++11 standard guarantees that you must not protect the single characters written to std::cout. Each character will atomically be written. Of course, it is possible that more output statements, like in the example, will interleave. But that is only an optical issue. The program is well-defined. The remark is valid for all input and output streams.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Be part of my mentoring programs:

 

 

 

 

Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.

Mutex

Mutex stands for mutual exclusion. It ensures, that only one thread can access a critical section.

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// coutSynchronized.cpp

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

std::mutex coutMutex;

class Worker{
public:
  Worker(std::string n):name(n){};
 
    void operator() (){
      for (int i= 1; i <= 3; ++i){
	// begin work
	std::this_thread::sleep_for(std::chrono::milliseconds(200));
	// end work
	coutMutex.lock();
	std::cout << name << ": " << "Work " << i << " done !!!" << std::endl;
	coutMutex.unlock();
      }
    }
private:
  std::string name;
};


int main(){

  std::cout << std::endl;
  
  std::cout << "Boss: Let's start working." << "\n\n";
 
  std::thread herb= std::thread(Worker("Herb"));
  std::thread andrei= std::thread(Worker("  Andrei"));
  std::thread scott= std::thread(Worker("    Scott"));
  std::thread bjarne= std::thread(Worker("      Bjarne"));
  std::thread andrew= std::thread(Worker("        Andrew"));
  std::thread david= std::thread(Worker("          David"));
  
  herb.join();
  andrei.join();
  scott.join();
  bjarne.join();
  andrew.join();
  david.join();
  
  std::cout << "\n" << "Boss: Let's go home." << std::endl;
  
  std::cout << std::endl;

 

The key difference to the first example is lines 19 to 21. By invoking the methods coutMutex.lock() and coutMutex.unlock(); you define the exclusive section. This section can only be accessed by, at most, a single thread. The access to std::cout is synchronized, and the mess becomes harmonious.

bossWorkerSynchonized

 

What's next?

Mutexes have a lot of issues, which I will discuss in the next post. (Proofreader Alexey Elymanov)

 

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

 

My special thanks to Take Up code TakeUpCode 450 60

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall


Comments   

0 #1 relieve foot pain 2016-10-13 09:16
I happen to be writing to make you know what a amazing discovery my friend's girl
experienced studying your web site. She came to understand
a good number of issues, including what it is like to possess a very effective coaching heart to have the mediocre ones clearly understand specified impossible subject matter.
You truly did more than visitors' desires. Thank you for delivering the warm and friendly, dependable, informative not to mention unique tips on that topic to Jane.
Quote
0 #2 dis agrisi 2016-11-08 07:57
Thank you for thhe good writeup. It in factt was a amusement account
it. Look advanced to more added agreeable from you!
By the way, how could we communicate?
Quote
0 #3 Valerie 2016-12-17 09:38
incredibly remarkable snap-shot!
Quote
0 #4 Genevieve 2017-07-18 08:18
Appreciate this post. Let me try it out.
Quote
0 #5 Ines 2017-08-15 19:40
I am really pleased to glasnce at this website posts which includes lots of useful data,
thanks for providing these statistics.
Quote

Stay Informed about my Mentoring

 

Mentoring

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Course: The All-in-One Guide to C++20

Course: Master Software Design Patterns and Architecture in C++

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 4043

Yesterday 4371

Week 39850

Month 169975

All 12057741

Currently are 234 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments