首页 > 学院 > 操作系统 > 正文

CLH锁的实现

2024-06-28 16:02:19
字体:
来源:转载
供稿:网友

#include “pthread.h”struct clh_node{	struct clh_node* PRev;	unsigned int locked;}clh_node;struct clh_lock{	clh_node* tail;}clh_lock;clh_lock g_clh_lock;pthread_key_t myNode, myPred;void initCLHlock(){	g_clh_lock->tail->prev = NULL;	g_clh_lock->tail->locked = 0;}void lock(){	    clh_node* qnode = (clh_node*)pthread_getspecific(myNode);    qnode->locked = TRUE;		    clh_node* pred = getAndSet(qnode);//原子的得到队尾,并将qnode设为新的队尾。		    pthread_setspecific(myPred, pred);    while(pred->locked)    {    }}void unlock(){    clh_node* qnode = (clh_node*)pthread_getspecific(myNode);    qnode->locked = FALSE;    clh_node* pred = (clh_node*)pthread_getspecific(myPred);    pthread_setspecific(myNode, pred);//unlock时必须将myNode指向前面的Node}void main(){	pthread_key_create(&myNode, NULL);	pthread_key_create(&myPred, NULL); 	}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表