互斥锁代码中发生死锁
我开发了一个用户级线程库。在代码中,有时会发生死锁,但我无法弄清楚为什么会发生。以下是互斥锁定和解锁功能的代码:
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;
}
I have developed a user level thread library. In the code, deadlock occurs sometimes, but i am unable to figure out why 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
另一个线程可能会在您的
while
测试和交换之间获得锁定。您必须检查
__sync_val_compare_and_swap
的返回结果,如果不成功则需要重申。此外,用于跟踪所有者的代码将不起作用,因为在解锁过程中,您可能会删除其他线程写入的信息。
最好只有一个字段(用原子操作处理)来保存所有者的信息,如果没有,则为 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.