简体   繁体   中英

When mutex lock isn't enough?

I know multithreaded programming is supposed to be hard. But it seems things find a weird way of breaking. For instance, I have multiple threads both changing the colors of and writing to the console (its an error log).

There were 2 problems:

  • jambled text
  • color changes interfering/not at the right times

When I added a mutex lock to the section that changes console color and writes to the console, it helped with the jambled text (haven't seen any since the mutex lock) but the console color is still wrong.

So it appears a mutex is not enough, I am now thinking I will need a queue. and a single thread that waits on that queue and flushes it out when there's stuff in it, So my question is? how do you gauge when a mutex lock is enough? As soon as pipes/files/comm w/ another process is involved?

A mutex (such as boost/pthread mutex) will guarantee exclusive access to a shared resource between different threads (but not processes, you need a named semaphore for that).

It sounds like your shared resource is access to the terminal. Just because you lock it when you change the color, doesn't mean it will be locked when you decide to change the color. Both threads would lock the mutex before either writing to the terminal or changing color. Making two mutexes isn't overly necessary since you're still protecting a single shared resource (the terminal).

If a thread wants to both write text and change the color, the mutex must support recursive locking, such as recursive_mutex .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM