mardi 23 février 2021

cout in multithread WITHOUT LOCK in C++20

I'm writing in C++20. Here's a very simple program that asks three threads to print some string. For example, we ask thread 1 to print "This is thread1", and thread 2 to print "This is thread2", and thread 3 to print "This is thread3".

However, I notice that in the printThread function that passed into threads, if we are not using a lock, we can get print results that mingle among threads. Such as This is This thread2 is thread3. I would like to avoid such intervening, so I wrote my code with mutex:

#include <iostream>
#include <string.h>
#include <thread>
#include <mutex>
using namespace std;


mutex m_screen;
void printCnt()
{   
    lock_guard guard(m_screen);
    cout << "Func Start" << endl;
    // Fetch the thread ID of the thread which is executing this function
    thread::id threadID = this_thread::get_id();
    
    cout << "Thread [" << threadID << "] has been called " endl;
    
    
}

// g++ foo.cpp =pthread

int main(){
    thread t1(printCnt);
    thread t2(printCnt);
    thread t3(printCnt);

    t1.join();
    t2.join();
    t3.join();

    cout << "done" << endl;
    
}

I wonder if there's any way that can achieve the same effect like mutex, but without a lock?

Aucun commentaire:

Enregistrer un commentaire