开发者

Using Mutexes correctly

What data type is a mutex?

I want to set an int as a mutex.

I see that the locks are set to ints and a mutex is declared as so pthread_mutex_t mtx where does one set the data type for the mutex or connect the mutex to开发者_开发百科 the variable?


I think you're mistaken about how mutexes work. They don't have a type (other than pthread_mutex_t obviously).

You can use them to protect a shared resources by making the threads that manipulate the resource all lock the same mutex when they need to operate on that resource.

What happens then is that, since only one thread at a time can hold the mutex locked, the other threads trying to access the shared resource will be blocked.

Once the thread that got the lock has finished using that resource, it must unlock the mutex - otherwise the other threads will block forever.

The exact nature of the resource you "protect" with this mutex is up to you. It could be a simple int, a complex structure, some hardware resource... You're responsible for making sure that all accesses to that resource from your code always locks and unlocks the mutex you created to protect it.

A reference you might find usefull: POSIX Threads Programming


From what I know in OS , mutex is a semaphore but can only takes two values 0 or 1 . A semaphore is like a lock that prevents many processes from accessing the same shared memory section (called critical section) at the same time which cause wrong results .

You enclose the critical section with methods that protect it from being accessed by multiple processes in the same time

wait(s) // decrement semaphore
//execute cs
signal(s) //increment semaphore (allow other processes to execute cs)

wait (S) { 
while S <= 0
; // no-op
S--;
{
signal (S) { 
S++;
{

In short mutex is a way to protect against synchronization problem . You can refer to slide 20 here OS-book.com

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜