Skip to content
Advertisement

pthread not waiting for mutex lock threadFinished

Hi below is my coding snippet

JavaScript

When statement1 & statement2 are commented I am expecting child thread to change my testrunning variable first before main thread but it is working properly only when statement1 and statement2 are uncommented.
My question is why in child thread mutex lock is not locking my testrunning variable . it is allowing main thread to modify testrunning variable.

Advertisement

Answer

When accessing a variable concurrently from multiple threads, each thread needs to protect access to it via the same mutex. The main() thread fails to do so.

To correct this you could change main()‘s while-loop like this:

JavaScript

Also you might like to consider narrowing locking to where it is necessary inside the thread-function like this:

JavaScript

You should added error checking to all library calls in case a failure would influence the remaining execution.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement