开发者

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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜