C + + multithread correlation (thread, mutex, atomic message queue) under Linux



  • wsl ubuntu 18.04 LTS
  • gcc version 7.5.0

In fact, this is not important, just a sense of ceremony, HH。 However, it must be implemented under Linux system. It is not allowed on Windows platform. C + + does not use this library to implement multithreading on Windows platform

Time slice rotation



using namespace std;

void func(int i,int times){
    puts("thread id: ");
    for(int i=0;i<=times;i++)
        printf("%d ",i);


G + + main.cpp - O main - lpthread # here - lpthread is a linked thread library, which is very important. If it is not added, it will fail to compile

If you run the program repeatedly, you will find that the output is different each time. This is the result of the rotation of different thread time slices

Thread synchronization



using namespace std;

int n;

void func() {
	for (int i = 0; i < 10000; i++)
int main() {
	thread th[100];

	for (thread &it : th)
		it = thread(func);

	for (thread &it : th)

	cout << n << endl;

	return 0;

It should be output logically1000000, but it doesn’t. It’s often less than this value. Because each thread has simultaneous accessnIn this case, we need to use mutex

Why can’t you use STD:: atomic?

staymutexCommon in Librarystd::mutexandstd::atomicCan achieve mutually exclusive access. We often use it in order to pursue higher efficiencystd::atomicinstead ofstd::mutex, andstd::atomicIt is more convenient and easy to understand, but if we want to usestd::atomicandstd::queueIt is not feasible to implement message queuing. Next, I will make a general explanation according to the information I find.

  • First put a rough explanation of the boss on stackoverflow

    A) atomic > fifo;

    B) queue > fifo;

    Both methods are not possible. A can’t even compile correctly. B can read and write atomic operations, but it can’tqueueFor examplepop(), push()Other operations

  • first,atomic varIn,TMust be of typeTriviallyCopyable(translated as)Copy unchanged)。 So it isTriviallyCopyableAnd? The documentation is as follows

    Scalar types scalar types

    • Scalar type is relative to compound type: scalar type can only have one value, while compound type can contain multiple values. Composite types are composed of scalar types.
    • In C language, integer type (int, short, long, etc.), character type (char, wchar_t, etc.), enumeration type (enum), decimal type (float, double, etc.) and boolean type (bool) all belong to scalar type. A scalar type data can only contain one value
    • Struct, array and string all belong to composite types. A composite type of data can contain multiple scalar types or other composite types.
    • Rivial copyable classes, i.e. classes satisfying following requirements

      • At least one copy constructor, move constructor, copy assignment operator, or move assignment operator is eligible. There must be a copy constructor, or a move constructor, or a copy assignment operator, or a move assignment operator
      • Every eligible copy constructor (if any) is trivial
      • Every eligible move constructor (if any) is trivial
      • Every eligible copy assignment operator (if any) is trivial
      • Every eligible move assignment operator (if any) is trivial
      • Has a trivial non deleted destructor
    • Arrays of triviallycopyable objects(TriviallyCopyable)Array of objects

      (supplement: what is a trivial class function? To put it simply, if class T satisfies: 1. The function is not provided by the user, that is, it is implicitly defined or preset; 2. T has no virtual member function; 3. T has no virtual base class; 4. It isTThe copy constructor selected by each direct base class of is trivial; 5. Copy constructors selected for non static members of each class type (or class type array) of T are trivial)

So I talked a lot, which means one thing,usestd::atomicandstd::queueTo implement message queuing is not feasible!

Implementation pairqueueThe operation protection of can only be usedmutex!