嘗試用c11的條件變數和mutex寫了一個讀寫鎖,c11條件變數
大家多多指正哈~
https://github.com/fishCi/c11/blob/master/rwlock.cpp
#include<thread>#include<mutex>#include<iostream>#include<unistd.h>#include<condition_variable>using namespace std;class rwlock { private: mutex _lock; condition_variable _wcon, _rcon; unsigned _writer, _reader; int _active; public: void read_lock() { unique_lock<mutex> lock(_lock); ++_reader; while(_active < 0 || _writer > 0) _rcon.wait(lock); --_reader; ++_active; } void write_lock() { unique_lock<mutex> lock(_lock); ++_writer; while(_active != 0) _wcon.wait(lock); --_writer; _active = -1; } void unlock() { unique_lock<mutex> lock(_lock); if(_active > 0) { --_active; if(_active == 0) _wcon.notify_one(); }else{ _active = 0; if(_writer > 0) _wcon.notify_one(); else if(_reader > 0) _rcon.notify_all(); } } rwlock():_writer(0),_reader(0),_active(0){ }};void t1(rwlock* rwl) { while(1) { cout << "I want to write." << endl; rwl->write_lock(); cout << "writing..." << endl; sleep(5); rwl->unlock(); sleep(5); }}void t2(rwlock* rwl) { while(1) { cout << "t2-I want to read." << endl; rwl->read_lock(); cout << "t2-reading..." << endl; sleep(1); rwl->unlock(); }}void t3(rwlock* rwl) { while(1) { cout << "t3-I want to read." << endl; rwl->read_lock(); cout << "t3-reading..." << endl; sleep(1); rwl->unlock(); }}int main(){ rwlock* rwl = new rwlock(); thread th1(t1,rwl); thread th2(t2,rwl); thread th3(t3,rwl); th1.join(); th2.join(); th3.join(); return 0;}
什是讀寫鎖?用java設計一個簡單的讀寫鎖
package com;
import java.util.Date;
public class InterruptTest {
public static void main(String args []){
MyThread test=new MyThread();
test.start();
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
test.interrupt();
}
}
class MyThread extends Thread{
public void run(){
while(true){
System.out.println("---"+new Date()+"---");
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
return ;
}
}
}
}
條件變數 教
pthread_mutex_lock(&q);
while(work==null)
pthread_cond_wait(&r,&q);
//代碼
pthread_mutex_unlock(&q);
pthread_mutex_lock(&q);
//代碼
pthread_nutex_unlock(&q);
pthread_cond_signal(&r);
大俠已經解釋得差不多了,我只補充一下。
1、線程2 並沒有等待訊號量,所以線程1裡沒必要加上
pthread_cond_signal(&cond2);
2、線程1在 wait signal 時會自動解鎖,所以並不會出現死結的情況