Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do scanf(), std::cin behave on multithreaded environment?

I'd like to state my problem using an example.

Assuming there is an array of N /*(N>>1)*/ threads which are set to run this function:

void Process() {
    //Some thread safe processing which requires in-deterministic computation time

    unsigned char byte;
    std::cin >> byte;
}

Once all of them are started simultaneously, what does happen? How are concurrent std::cin accesses handled? What does the end-user who operates on console see/experience?

Edit: There is one more thing I'd like to add. Is the code below safe enough to abandon the idea of using std:cin only in one (probably main) thread?

void Process() {
    //Some thread safe processing which requires in-deterministic computation time

    //Mutex lock
    unsigned char byte;
    std::cin >> byte;
    //Mutex unlock
}
like image 487
diegoperini Avatar asked Sep 17 '13 07:09

diegoperini


1 Answers

I would say, the result is not predictable without mutexes.

If you use a mutex, everything is fine. That's what mutexes are for.

like image 187
Konstantin Avatar answered Sep 23 '22 11:09

Konstantin