I am using c++ with boost threads, locks mutexs and all that good stuff.
Two threads A and B. A is a networking thread where there is information coming back and forth from the client. B is a worker with variables which needs to be thread safe.
There are multiple threads from the class A and B is just a single thread. Instances of A will be added to B’s list of jobs and A will lock until B has completed the task. (The thread safe list of jobs works fine)
A adds the job to B and then locks, however in most cases before A has locked. B will have processed the job and have (tried to) release the lock before A has applied it. Resulting in As dead lock.
I am not sure what I should be doing here. I could post code but I would imagine is easier to discuss conceptually.
The actual problem is in that the B gets the task and starts to execute it before the thread from A locks. The result you observer can be classified as “missed notification”. Quite often when trying to implement two-way synchronization with i.e. mutexes or other simple synchronizers.
You have to make sure that the B does not notify unless A is already waiting, OR you can make sure that the notification is not missed.
While the first way may be a quite tricky to peform , the latter is very simple: use a semaphore (or manual-reset-event or (…)).
On semaphores:
while:
Note that the semaphore UNLOCK is nonblocking if count
Instead of using a semaphore, you can use also events with manual set/reset. Just let the A create-and-lock on the event that is OFF and let the B set it ON.