tags:

views:

60

answers:

3

I am writing a C UNIX program that is threaded and shares one variable across all threads. What would be the easiest way to acquire a lock on this variable? I can't find any small libraries just for locking in UNIX.

Any suggestions how to do this?

Thanks, Boda Cydo.

+1  A: 

There are a wide variety of ways to do this, and I encourage you to explore them all, but a good starting point is the mutex implementation in pthreads, which has several things going for it: pthreads is available on a lot of platforms and it's well-designed.

Hao Lian
+4  A: 

There's pthread_mutex_lock, if you're already using pthreads.

Quick example, where counter is the shared variable and mutex is a mutex variable of type pthread_mutex_t:

/* Function C */
void functionC()
{
   pthread_mutex_lock( &mutex );
   counter++;
   pthread_mutex_unlock( &mutex );
}
eldarerathis
+3  A: 

You cannot lock a variable. The subject of intensive research, STM is a promising candidate but nobody has yet written an operating system that uses it.

No, you can only block code that tries to access that variable. Which is typically done with a mutex.

Hans Passant