Re: Question about multithreads



On Tuesday 31 October 2006 22:00, Paul Pogonyshev wrote:
Tomasz Jankowski wrote:
I generaly know how to write multithreads applications (so far code,
which I wrote works fine). However I'm not sure if I should always lock
and unlock mutex when I'm accesing some global data from thread. I know,
that i'm obligated to sorround with mutex's lock and unlock each part of
code, which acces some global variables, but I wonder if I can omit mutex
locking when I do such fast thing like reading drom integer variable. Can
I do it?

AFAIK, integer reading is atomic.  So you probably can since mutex locking
probably indicates you just protect against write-in-the-middle case, not
performing any synchronization.

No values are guaranteed by POSIX to give atomic reads when they are capable 
of being modified by another thread, but in practice an integer value is 
likely to be atomic, so the value seen will be a value which will have been 
valid at some indeterminate time in the past.

However, it's not just a matter of atomicity, but of memory visibility.  On a 
multi-processor system, you can only omit a mutex if you don't care whether 
other threads see out of date values (that is, different threads seeing 
different values for the same variable).  Normally, however, you want 
different threads to see the same value for the same variable.

Chris




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