简体   繁体   English

什么时候互斥锁还不够?

[英]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).例如,我有多个线程同时更改 colors 并写入控制台(它是一个错误日志)。

There were 2 problems:有2个问题:

  • 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).互斥体(例如 boost/pthread 互斥体)将保证对不同线程之间的共享资源的独占访问(但不是进程,您需要一个命名信号量)。

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 .如果线程既要写入文本又要更改颜色,则互斥锁必须支持递归锁定,例如recursive_mutex

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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