Re: Curious global variable bug? Bad assumptions on my part?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Tynan,

First off, C is not a multi-threaded language.

That doesn't mean you can't do multi-threaded programming in it.  It just
means that the language does not support multi-threaded programming.  (Just
as C is not an object-oriented programming language, but you can do
object-oriented programming in it just fine -- with a good heaping helping
of discipline and diligence.)

Adding volatile to the g_counter tells the compiler not to optimize away
access to the variable, as the variable can change "at any time".

That may sound like just the thing for multi-threaded access to the same
variable -- but it's not sufficient.

Even though the compiler is no longer going to optimize away access to the
variable, the hardware can still effectively isolate the two threads from
one another, such that neither thread is aware that the g_counter variable
has changed.

Why?  Because each thread could run with the variable stored in separate
caches.

That's where a bolt-on library like pthread (POSIX threads) comes into play.

Using pthread routines, you can programmatically make sure that all the
caches are sync'd so that each core has the same view of the state of the
variable.  (If C was a multi-threaded language, it would have these kinds of
directives as primitives.)

Google turned up this nice tutorial:
https://computing.llnl.gov/tutorials/pthreads/

Read the sections on Mutex Variables, and on Condition Variables.

There are several good books available on PThread programming... I recommend
anything from Addison-Wesley or O'Reilly publishers on the topic.  (The
books I read on PThread programming are 10+ years old, and I can't find them
at the moment to recommend them in particular.)

HTH,
--Eljay


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux