Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to poll for a variable written by other threads in a C program?

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?

like image 837
Thiago Padilha Avatar asked Jan 19 '14 13:01

Thiago Padilha


People also ask

Are local variables shared between threads in C?

But: No, threads do not share real local variables.

What is main thread in C?

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).

How do threads work in C?

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.

Is C single threaded?

I was recently reading "The C Programming language" by Ritchie, I noticed that C is a single threaded language.


1 Answers

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.

like image 64
James Hopkin Avatar answered Oct 12 '22 19:10

James Hopkin