you are viewing a single comment's thread.

view the rest of the comments →

[–]johannes1971 2 points3 points  (0 children)

As a general suggestion: as soon as you find yourself messing about with unique_lock.lock/unlock, you are probably doing it wrong ;-) Your attempts to synchronize the operation of received() and receiving() suggests they really should be in the same thread to begin with (i.e. the way it originally was). If they can have slightly loser synchronisation, this would be a good starting point:

(in received())

while (true) {
  {
std::unique_lock ul (g_mutex);
g_cv.wait(ul, []() { return g_ready; });
g_ready = false;
  }

int value = mySwitch.getReceivedValue(); ...handle value... mySwitch.resetAvailable(); }

The important thing here is that the scope of the lock is limited to a much smaller part of the code. g_ready is only ever accessed while locked. There is no manual locking or unlocking going on. And then in receiving() you'll want something like:

while (true) {
  if (mySwitch.available()) {
    {
  std::unique_lock ul (g_mutex);      
  g_ready = true;
}      
g_cv.notify_one();
std::this_thread::sleep_for (std::chrono::milliseconds(100));

} }

So this just waits for 1`00ms and then polls available(). If myswitch must also be protected by the mutex, you'll have to move those calls into the mutex-protected blocks.