C++ 读锁和写锁

读锁

所用到的数据结构是读写锁,初始化之后,即可以当读锁,又可以当写锁。

# include
# include

using namespace std;
pthread_rwlock_t flock=PTHREAD_RWLOCK_INITIALIZER;//初始化
void hello(char c)
{

    for(int i=0;i<5;i++) {
        pthread_rwlock_rdlock(&flock);//上读锁
        cout << c << " " << i << endl;
        pthread_rwlock_unlock(&flock);//解锁
    }
}
int main()
{
    thread t0 (hello,'a');
    thread t1 (hello,'b');
    t0.join();
    t1.join();
}

结果如下

ab  00

ab  11

ab  22

ab  33

ab  44

写锁

# include
# include

using namespace std;
pthread_rwlock_t flock=PTHREAD_RWLOCK_INITIALIZER;//初始化
void hello(char c)
{

    for(int i=0;i<5;i++) {
        pthread_rwlock_wrlock(&flock);//上写锁
        cout << c << " " << i << endl;
        pthread_rwlock_unlock(&flock);//解锁
    }
}
int main()
{
    thread t0 (hello,'a');
    thread t1 (hello,'b');
    t0.join();
    t1.join();
}

结果如下

a 0
a 1
a 2
a 3
a 4
b 0
b 1
b 2
b 3
b 4

你可能感兴趣的:(C++ 读锁和写锁)