Does this section of code require a mutex?

Yes, you must first use a mutex to protect reads and writes to interruptRequested in respective blocks.

Yes, you must first use a mutex to protect reads and writes to interruptRequested, in respective blocks. Even if it appears to work as expected, it may not actually. A 99% success rate is not acceptable in software.As well, your test program is trivial - chances are good that it would (silently or mysteriously) fail in the real world.

Using volatile (or atomics, in many cases) as a replacement for a lock is a bad idea. This model will eventually fail, although it often appears to work correctly under light loads. There are a few corner cases, but you should abandon associations of volatile being a replacement for a proper design which uses locking.

In fact you can test this by making interruptRequested an int, and using only increment/decrement. Under heavy loads - you can quickly exceed 0...1. You will often use volatile and/or atomics when declaring/reading/writing interruptRequested (again, I recommend an int/inc/dec/bounds checks, especially while you are learning).

If the reads and writes are all locked (which they should be in this case), using atomic reads/writes won't help. Regarding your program, conditions (pthread_cond_t) may be a good choice.

As written, this code is not necessarily guaranteed to work because the compiler might optimize away the check for interruptRequested inside of the worker thread because it's never written inside of the function. This would mean that the generated code may just have a while (true) loop in it (or something equivalent to it). To prevent this from happening, you somehow need to ensure that the compiler recognizes that the variable might be modified elsewhere.

You could do this by marking interruptRequested volatile, which indicates to the compiler that it shouldn't be optimized away. Using a mutex is also a good idea, because most compilers are smart enough to recognize that the use of a mutex indicates that the variables referenced inside of the mutex may be modified externally.

1 yes, using the volatile attribute is a good idea – fabrizioM Mar 19 at 20:16.

I think in general shared data should be handled with mutex. In this specific case only one thread updates the control variable, so it might be too much using a mutex. You can put a time sleep in the active loop of few milliseconds to make the main loop active from time to time.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions