Consider the following snippet of C code:
int flag = 0;
/* Assume that the functions lock_helper, unlock_helper implement enter/leave in
* a global mutex and thread_start_helper simply runs the function in separate
* operating-system threads */
void worker1()
{
/* Long-running job here */
lock_helper();
if (!flag)
flag = 1;
unlock_helper();
}
void worker2()
{
/* Another long-running job here */
lock_helper();
if (!flag)
flag = 2;
unlock_helper();
}
int main(int argc, char **argv)
{
thread_start_helper(&worker1);
thread_start_helper(&worker2);
do
{
/* doing something */
} while (!flag);
/* do something with 'flag' */
}
Questions:
Is it it possible that 'flag' will always be 0 for the main thread(and it becomes stuck in the do/while loop) due to some compiler optimization?
Will the 'volatile' modifier make any difference?
If the answer is 'depends on a feature provided by the compiler', is there any way I can check for this 'feature' with a configuration script at compile-time?
But: No, threads do not share real local variables.
When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread).
A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. C does not contain any built-in support for multithreaded applications.
I was recently reading "The C Programming language" by Ritchie, I noticed that C is a single threaded language.
The code is likely to work as is, but is somewhat fragile. For one thing, it depends on the reads and writes to flag
being atomic on the processor being used (and that flag
's alignment is sufficient).
I would recommend either using a read lock to read the value of flag
or use functionality of whatever threading library you are using to make flag
properly atomic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With