简体   繁体   English

std :: thread和std :: mutex问题

[英]std::thread and std::mutex issue

I've got a global buffer (uint8_t dataBuffer[]) which a bluetooth communication thread is continuosly updating. 我有一个全局缓冲区(uint8_t dataBuffer []),蓝牙通信线程正在不断更新该缓冲区。 At any given time my main program thread could access this same data buffer. 在任何给定的时间,我的主程序线程都可以访问相同的数据缓冲区。 The question is how do I prevent the main thread accessing the buffer while the other thread is updating it and vice versa? 问题是如何防止主线程在另一个线程更新缓冲区时访问缓冲区,反之亦然?

At the moment my bluetooth thread does mutex lock() and unlock() around the buffer update. 目前,我的蓝牙线程在缓冲区更新过程中互斥了lock()和unlock()。 I have another mutex lock() and unlock() in my main thread as well when I'm accessing the data but this doesn't seem to work properly. 当我访问数据时,我的主线程中还有另一个互斥体lock()和unlock(),但这似乎无法正常工作。 For some reason I keep getting a lot of checksum errors which I'm pretty sure comes from a threading issue as I have another single threaded test app which is communicating with the same device pretty much flawlessly. 由于某些原因,我不断收到很多校验和错误,我可以肯定这是由于线程问题引起的,因为我有另一个单线程测试应用程序,该应用程序几乎可以与同一设备进行完美通信。

This is cut down version of what I do in my communication thread: 这是我在通讯线程中所做的工作的简化版本:

uint8_t dbuf[14];
while(1)
{
    if(!run)
        break;

    // Read data... //

    mtx1.lock();
    memcpy(dataBuffer, dbuf, 14);
    mtx1.unlock();
}

And in my main thread I have something like this: 在我的主线程中,我有类似以下内容:

mtx2.lock();
// Do something with dataBuffer
mtx2.unlock();

Is there something fundamentally wrong with what I'm doing? 我所做的事情有根本的错误吗?

It's hard to tell, but it sounds like you're using two mutexes to protect one piece of data. 很难说,但是听起来您正在使用两个互斥对象来保护一个数据。 That won't work. 那行不通。 We want one mutex. 我们想要一个互斥锁。

Let's look at a full example: 让我们看一个完整的例子:

#include <thread>

std::mutex mutex;
int treasure;

void worker(int value) {
    while(true) {
        std::lock_guard<std::mutex> lock(mutex);
        treasure = value;
    }
}

int main() {
    auto t1 = std::thread(worker, 4);
    auto t2 = std::thread(worker, 5);

    t1.join();
    t2.join();
}

Things to note: 注意事项:

  1. The std::mutex is shared between the two threads. std::mutex在两个线程之间共享。
  2. Each thread uses a std::lock_guard when it wants to access the shared data. 每个线程在要访问共享数据时都使用std::lock_guard You could also use a std::unique_lock . 您还可以使用std::unique_lock

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

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