deadlock occuring in mutex code [closed]
I have developed a user level thread library. In the code, deadlock occurs sometimes, but i am unable to figure out w开发者_StackOverflow社区hy it is happening. Here is the code for mutex lock and unlock functions:
int gtthread_mutex_lock(gtthread_mutex_t *mutex)
{
if(!mutex) //checks if mutex is null
return -1;
while(mutex->available==1); //spin locks if mutex is already locked by someone else
__sync_val_compare_and_swap(&mutex->available,0,1); //atomic function to swap value 0 with 1
mutex->owner=node->th;
return 0;
}
int gtthread_mutex_unlock(gtthread_mutex_t *mutex)
{
if(!mutex) return -1;
if(mutex->available)
{
mutex->available=0;
mutex->owner=NULL;
}
return 0;
}
Another thread might obtain the lock between your while
test and the swap.
You'd have to check the return of __sync_val_compare_and_swap
and reiterate if it didn't succeed.
Also your code for keeping track of the owner will not work, because in your unlock you may delete the information that some other thread has written.
Better you just have one field (handled with atomic operations) which holds the info on the owner and that is 0 if there is none.
精彩评论