A
A
alienstone2015-11-17 12:16:34
linux
alienstone, 2015-11-17 12:16:34

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.

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
X
xmoonlight, 2015-11-17
@alienstone

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

M
Mercury13, 2015-11-17
@Mercury13

And surely you can't?
I would do this...
Stream 1.

мютекс2.войди
поток2.старт
повторяй 10 раз
  мютекс1.войди
  writeln
  мютекс2.выйди
поток2.дождись
мютекс2.выйди

Stream 2.
повторяй 10 раз
  мютекс2.войди
  writeln
  мютекс1.выйди

Notice we enter one mutex and exit another. I'll check and write back.
The only debatable "means of synchronization" is on thread 1 to wait for thread 2 to complete.

E
Eddy_Em, 2015-11-17
@Eddy_Em

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.

O
Oleg Tsilyurik, 2015-11-17
@Olej

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 ); 
}

Here, there are no variables except for the mutex ... - compile, execute, plant ;-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question