开发者

deadlock occuring in mutex code [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜