Skip navigation.
 
mlRe: Re: Threads and synchronization
FROM : Michael Ash
DATE : Wed Aug 23 17:47:43 2006

On 8/23/06, <email_removed> <<email_removed>> wrote:
> If I have a simple GUI/task thread model (i.e., the task does all the
> "work", while the GUI interacts with the user/displays content, etc),
> it would seem like a simple lock/flag system would be enough--i.e.,
> the GUI sets a variable "start" ), and the task starts up, sending
> progress back via performTaskOnMainThread:.


You will have to poll this variable to see if it's set, and polling is
bad. Instead, use an NSConditionLock and signal through that, or just
start a new thread every time. This eliminates your one piece of
shared memory and everything becomes simple.


>  For OSMemoryBarrier, my
> understanding is that it must be used anytime writes happen to shared
> memory--if ti's not used, there's no guarantee that the other side
> "notices" that the data has changed


This is not the case. OSMemoryBarrier orders memory accesses. On some
architectures (PPC certainly, I don't know about x86), it's possible
that memory stores will be performed in a different order than they
show up in code. So let's say you had this bit of code (it's terrible,
don't copy the design, just for illustration) looping in a thread:

  while(!x) ; // do nothing until x is set
  printf("y = %d\n", y);

Then you execute this in another thread:

  y = 42;
  x = 1;

On a multiprocessor system it's possible that the other CPU will see
"x = 1" first. The other thread would then run, and print a stale
value of y. You fix it by inserting an OSMemoryBarrier between the two
assignments.

For a single variable that you need to force out to memory when you
assign to it, mark it as volatile.

The call to OSMemoryBarrier will *probably* force a store to a
non-volatile variable to be performed, but it's not guaranteed and
that's not its purpose.

Mike

Related mailsAuthorDate
mlThreads and synchronization (was: Re: Secondary run loops?) Cem Karan Aug 10, 17:27
mlRe: Threads and synchronization John Stiles Aug 10, 17:36
mlRe: Threads and synchronization Cem Karan Aug 10, 17:56
mlRe: Threads and synchronization AgentM Aug 10, 19:57
mlRe: Threads and synchronization marc@mac.com Aug 23, 16:59
mlRe: Re: Threads and synchronization Shawn Erickson Aug 23, 17:29
mlRe: Re: Threads and synchronization Michael Ash Aug 23, 17:47
mlRe: Threads and synchronization Chris Suter Aug 24, 02:01