Re: [Dev-C++] Volatile in multithreading?
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2009-08-17 10:19:42
|
No real problems with using volatile variables to synchronize multiple
threads as long as the variable is small enough that it can be atomically
read/written.
If you have specific questions relating to the articles you have found,
you must post a link to the articles.
Volatile variables works well for polling operations. But there are other
methods available to synchronize threads, where a thread may sleep until
you send it an event. And there are signals, critical sections and mutexes
that can be used too. There are often more than one way to skin a cat, and
the developer has to select which method works best for each individual
case.
/pwm
On Mon, 17 Aug 2009, Philip Bennefall wrote:
> Hi folks,
>
> I've been using volatile for flag variables to signal that events have occured between threads, always making sure that only one thread writes to it at a time while another thread regularly checks for its value. Like this:
>
> volatile int global_flag=0;
>
> void func_1()
> {// Do work.
> // Do work.
>
> global_flag=1;
> }
>
> void func2() // In another thread.
> {
> while(global_flag==0)
> {
> // Do other stuff if needed.
> }
> // Flag changed, now we can proceed.
> }
>
> This has been working fine on my X86 machine running Windows Xp for months without a glitch, but I've recently read up on volatile and found some articles claiming that this is a poor method to accomplish said goal. All I am trying to achieve is a flag variable that is sure not to be read in the middle of a writing operation, but I'm not certain now that I'm going about it the right way. I use MinGw's heaviest optimization setting. Can anyone shed some light on this perhaps? Would I really need to use a synchronization object like a critical section, or is there in fact a simpler method?
>
> Thanks in advance.
>
> Regards
> Philip Bennefall
|