简体   繁体   中英

std::thread and std::mutex issue

I've got a global buffer (uint8_t dataBuffer[]) which a bluetooth communication thread is continuosly updating. 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. 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. 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.
  2. Each thread uses a std::lock_guard when it wants to access the shared data. You could also use a std::unique_lock .

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