Linux多线程同步方式总结

Contents

线程同步方式的逻辑

互斥锁

lock\unlock,这样就可以构成一个原子操作

/*mu is a global mutex*/

while (1) {                /*infinite loop*/
  mutex_lock(mu);           /*aquire mutex and lock it, if cannot, wait until mutex is unblocked*/
  if (i != 0) i = i - 1;
  else {
    printf("no more tickets");
    exit();
  }
  mutex_unlock(mu);         /*release mutex, make it unblocked*/
}

条件变量

经常保存为全局变量,并和互斥锁合作。

/*mu: global mutex, cond: global codition variable, num: global int*/
mutex_lock(mu)

num = num + 1;                      /*worker build the room*/

if (num <= 10) {                     /*worker is within the first 10 to finish*/
    cond_wait(mu, cond);            /*wait*/
    printf("drink beer");
}
else if (num = 11) {                /*workder is the 11th to finish*/
  cond_broadcast(mu, cond);         /*inform the other 9 to wake up*/
}

mutex_unlock(mu);

cond_wait :
1. 释放互斥锁mu,使得其他线程能够访问,
2. 同时等待,直到cond的通知。这样符合条件的线程就开始等待。
3. 接收道通知之后,cond_wait到unlock部分重新被上锁,接收到通知的线程依次执行。

cond_broadcast:
1. 负责给所有调用cond_wait的线程发送通知,以便让那些线程恢复运行。

读写锁

  • 与互斥锁类似;共有三种状态:
  1. 共享读取锁 (shared-read)
  2. 互斥写入锁 (exclusive-write lock)
  3. 打开(unlock)

– 如果一个线程获得R锁,其他线程也可以获取R锁,但是如果此时,有线程想要获得W锁,需要等待所有获得R锁的线程释放
– 如果一个线程获得了W锁,其他线程必须等它释放才能获得R或者W锁
– 读写锁使得读操作可以共享,写操作被保护


已发布

分类

来自

标签: