Answer the question
In order to leave comments, you need to log in
Why is it not possible to synchronize the output of two threads when using two mutexes?
Hello,
There was a task - to synchronize the output of the parent and child threads (there are only 2 of them): first, the parent thread displays the first line, then the child, then the parent's second line, etc. Only mutexes can be used, other means of synchronization are prohibited. I cannot immediately prove why this is impossible. Tell me please.
Source text of the task:
Write a program that creates a thread. Use the default attributes. The parent and newly created threads should print out ten lines of text. Modify the program so that the output of the parent and child threads is synchronized: first the parent thread outputs the first line, then the child, then the parent second line, and so on. Use mutexes.
Explicit and implicit transfers of control between threads (sleep(3C)/usleep(3C), sched_yield(3RT)) and idle loops are allowed only at the initialization stage.
Prove that this problem cannot be solved using two mutexes without using other means of synchronization.
Answer the question
In order to leave comments, you need to log in
https://en.wikipedia.org/wiki/%D0%9C%D1%8C%D1%8E%D...
Only one thread can own an object protected by a mutex at a time
And surely you can't?
I would do this...
Stream 1.
мютекс2.войди
поток2.старт
повторяй 10 раз
мютекс1.войди
writeln
мютекс2.выйди
поток2.дождись
мютекс2.выйди
повторяй 10 раз
мютекс2.войди
writeln
мютекс1.выйди
What nonsense? That's what mutexes were invented for. We lock the mutex in the parent, output a line, set some global key to 1, reset the mutex, wait until the key is 0. In the child, we wait until the key is 1, lock the mutex, output a line, reset the key, unlock the mutex.
If not threads (pthreads) are used, but processes (fork), then you need to remove buffering or flush buffers after each write.
See my answer with two mutexes in a comment to this answer.
If you are confused by a simple variable (flag) in the response of the Japanese Policeman ("What the hell?..." - which is completely fair ;-) ), then I will sketch out a different scheme for you - each of the threads does something like this:
while( true ) {
while( pthread_mutex_trylock( &mutex ) == EBUSY );
cout << "это мя строка, ура!" << endl;
pthread_mutex_unlock( &mutex );
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question