Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>No, this is not correct. You're almost there, but the big problem is that the Multiply and Increment functions should be using the <strong>same</strong> mutex.</p> <p>A mutex is an object that provides MUTual EXclusion. In other words, the point of a mutex is to prevent two threads from touching the same variable at the same time and causing unpredictable results. A mutex is kind of like a token that one thread at a time holds that gives it the "right" to access a certain variable (or set of variables). In this case, the variable you are trying to protect is <code>counter</code>. There must be one and only one mutex that controls the right to access <code>counter</code>. In your case, each thread will hold its own token that it thinks gives it the right to access counter, and so there will be unpredictable behavior.</p> <p>You "hold" a mutex by locking it. That's the point of the locks, and that's why you cannot "avoid" them. The entire point of the scoped locks is that, assuming you have only one mutex <code>m</code>, when one of the threads holds the lock on <code>m</code>, the other thread is guaranteed to not also be holding a lock on <code>m</code>. If you've coded correctly, holding a lock on <code>m</code> should be a prerequisite for accessing <code>counter</code>, and so the value of <code>counter</code> should be predictable.</p> <p>Now, regarding the <code>wait()</code>. A call to <code>wait()</code> means "I give up the lock on this mutex until someone else signals this condition, and then I want it back". In the mean time, the thread stops. So assuming you have only one mutex <code>m</code> and a condition <code>c</code>, and <code>lk</code> is a lock on <code>m</code>, the line <code>c.wait(lk)</code> means that the thread will give up the lock <code>lk</code> on <code>m</code>and then suspend execution until some other thread calls <code>c.notify_one()</code> (or <code>c.notify_all()</code>). When the waiting thread returns from the call to <code>wait()</code>, it will have automatically re-gained the lock <code>lk</code> on <code>m</code> and so is permitted to access <code>counter</code> again.</p> <p>Finally, these boost locks are "scoped" locks. This means that they are released automatically on destruction (when they go out of scope). So in this case, each function holds its lock until it exits, except for times when it has given up its lock to wait and has suspended execution pending a signal.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload