Friday, November 09, 2007

Re: "C and multithreading"

On debian planet. I read the C and multithreading post of Miriam Ruiz, but I don't agree with some conclusions:

First of all, I don't agree with Linus. C standard doesn't allow such optimizations. One of the driving point of C standard (and thus C) is that compiler should do what a programmer write, without much optimization, i.e. C should remain a low level language. It was iterated also for the principles of new C1X standard.

Second point. Volatile is not the right solution. volatile means that a variable should be read every time it is accessed, so the variable should not be but in registers (remember the nearly obsolete register keyword).

The problem of multi threading is not only that variables could changes (but this is a fact also of
single thread programs, when you write a signal handler [which are specified in C standard and which are handled correctly]), but for semaphores there are "barriers", i.e. you should not move read or write across such barriers.

What do volatile have with barriers? Nothing. If you read the standard (you can check also only the one page C appendix), you see that C specify what are the "standard" barrier, and they are nearly in all obvious points (i.e. a ";" is also a barrier), so moving instructions is "illegal" for C.
Ok. volatile had few other barriers, but across ";" there is already a barrier, so volatile is not the solution of barrier problem (AB locking).

References: see C wiki and C standard.

1 comment:

Ben Hutchings said...

Any multithreaded C program has undefined behaviour according to the standard, because the standard defines the behaviour of a single thread of execution. Sequence points - which, by the way, are not points, and do not form a sequence - have no synchronisation effects, and certainly don't provide any atomicity. Currently you have to look to other standards, or compiler documentation, for a definition of the memory model for a multithreaded program. POSIX threads could have defined it, but is sadly very vague.