How mutex works?


F1()
{
lock(&A);
dosomething()
releaselock(&A);
}

F2()
{
lock(&A);
dosomething();
releaselock(&A);
}
if Thread 1 is calling F1 and Thread 2 is calling F2.

Since same mutex variable is been used for both the funtions, suppose T1 locks(A) and will T2 wait for T1 to release the lock.

Here T1 & T2 are accessing different funcitons.

Can any one provide the details behaviour.??
I think you should read this http://www.cplusplus.com/forum/unices/90343/ topic, i think it's about the same thing you are asking.
The mutex does not guarantee that you will not be able to do that thing between the mutex loc and unlock. It's your duty to make sure that the whatever is between your lock /release is only done once.
For example your code should loke like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
F1()
{
  if(!mutex_locked(&A){
    lock(&A);
    dosomething()
    releaselock(&A);
    }
}

F2()
{
  if(!mutex_locked(&A){
    lock(&A);
    dosomething()
    releaselock(&A);
    }
}
Last edited on
For example your code should loke like:


In my understanding most mutex implementations will block on a lock call until they can get the lock, not simply continue on.

Your code does nothing in the case that the mutex is already locked which might not be intended behavior and certainly doesn't look right to me.
Let's make it look more like C++

1
2
3
4
5
6
7
8
9
10
11
F1()
{
    lock<mutex> lk(A);
    dosomething()
}

F2()
{
    lock<mutex> lk(A);
    dosomething();
}


suppose T1 locks(A) and will T2 wait for T1 to release the lock.

Yes, it will, that's the whole point: if T2 attempts to acquire a mutex that's currently held by T1, T2 goes to sleep until the mutex is released by T1.
Topic archived. No new replies allowed.