#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); }
新闻热点
疑难解答