c++ - std::thread and std::mutex issue -


I have a global buffer (uint8_t data buffer []) which is continuously updating a Bluetooth communication thread at any time mine The main program thread can access this data buffer. The question is how do I stop the main thread from reaching buffer, while the other thread is updating it and vice versa?

Right now my Bluetooth lock mute locks (around buffer updates). I have another Mutex lock () and unlock () also in my main thread when I'm accessing the data but it does not work properly. For some reason, I get many checksum errors, which I'm sure is that I come in the form of a threading issue because I have another single threaded test app, which is very easy to communicate with the same device without any fault Used to be.

What do I do in my communication thread:

  uint8_t dbuf [14]; While (1) {if (run!) Brakes; // Read the data ... // mtx1.lock (); Memcopy (Databaffer, DBFF, 14); Mtx1.unlock (); }   

And I have something like this in my main thread:

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

What am I missing in something?

It is difficult to say, but it appears that you have two mutes are using it. This will not work. We want one mutes.

We see a full example:

  #include & lt; Thread & gt; Std :: mutex mutex; Int Treasure; Zero worker (int value) {while (true) {std :: lock_guard & lt; Std :: mutex & gt; (Mutex) lock; Treasure = value; }} Int main () {auto t1 = std :: thread (worker, 4); Auto t2 = std :: thread (worker, 5); T1.join (); T2.join (); }   

Note:

  1. Two threads are shared between them.
  2. Each thread uses that when it wants to access the shared data you can use one too.

Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

.net - Creating a new Queue Manager and Queue in Websphere MQ (using C#) -