bodacydo
bodacydo

Reputation: 79549

What's the easiest way to acquire a lock on a shared variable for a UNIX C program?

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.

Upvotes: 0

Views: 2761

Answers (3)

eldarerathis
eldarerathis

Reputation: 36243

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 );
}

Upvotes: 4

Hans Passant
Hans Passant

Reputation: 942408

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.

Upvotes: 4

hao
hao

Reputation: 10238

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.

Upvotes: 1

Related Questions