[cpp-threads] Failed compare-and-swap

Boehm, Hans hans.boehm at hp.com
Wed Aug 1 00:03:20 BST 2007


> From: Herb Sutter
> > (As Alexander points out, a simple trylock can't tell the 
> difference 
> > in Posix.  On the other hand, a trylock followed by an unrelated 
> > successful synchronization operation can.)
> 
> Sorry, I missed this. What was the example?
> 
Thread 1:
	x = 1;
	pthread_mutex_lock(&l1);

Thread 2:
      /* Wait for l1 to be locked. */
	  while(pthread_mutex_trylock(&l1) == 0)
pthread_mutex_unlock(&l1);
      /* "synchronize memory" explicitly */
	  pthread_mutex_lock(&l2); pthread_mutex_unlock(&l2);
	assert(x == 1);

I believe the assertion is guaranteed not to fail by reasonable
interpretations of Posix rules.  It in fact can fail if
pthread_mutex_lock only has acquire semantics, since that would mean
that the two statements in thread 1 can effectively be reordered, and
the assignment to x can become visible after the lock acquisition.

I believe it's reasonably uncontroversial that the assertion should be
allowed to fail.  Requiring release semantics for pthread_mutex_lock is
expensive, and not useful for sane code.  (It's uncontroversial that the
above code does not qualify as "sane".)  It is also not required by Java
lock semantics, for example.

Having said that, I'm not sure whether there is a reasonable way to fix
this in the current Posix revision, except possibly with a vague
statement that memory operations preceding a lock acquisition may appear
to happen after it.  You really need to define a memory model for the
programming language first.  And I don't know how to make the timing
work for that.

Hans
    



More information about the cpp-threads mailing list