How to use mutex

前端 未结 1 1809
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 12:44

Where should i put the lock and unlock mutex in order for the threads to print alternatively? Thanks:D

Implement a program that creates two threads. The threads will pr

相关标签:
1条回答
  • 2021-01-29 12:52

    If you want the predictably ordered output A, B, A, B, A, B, the most appropriate tool to use is a single thread of control.

    To do it wastefully with two threads, you can define a shared variable called "turn" which indicates whose turn it is to print something. Each thread waits on a condition variable until the "turn" variable is equal to itself. Then it carries out the sequential task, sets the "turn" variable to another thread and signals the condition.

    0 讨论(0)
提交回复
热议问题