linux学习笔记9 锁
1.互斥锁
主要包括上锁,解锁,测试锁三种功能
锁的初始化:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
也可以用函数初始化:pthread_mutex_init(&mutex,NULL);
上锁:int pthread_mutex_lock(pthread_mutex_t *mutex)临界区域已经被锁了,就会阻塞,就会等待直到解锁了再抢占资源
解锁:int pthread_mutex_unlock(pthread_mutex_t *mutex)
测试锁:int pthread_mutex_trylock(pthread_mutex_t *mutex)临界区域已经被锁了,就会立刻退出。并且返回退出原因
简单的上锁和解锁程序举例
#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//这条语句执行完成静态锁的初始化,pthread_mutex_t是一个结构体,
//PTHREAD_MUTEX_INITIALIZER定义的一个结构体常量宏,
using namespace std;
void *thr1(void * agr)
{
while (1){
pthread_mutex_lock(&mutex);//上锁
cout<<"HELLO";
sleep(rand()%3);
cout<<"WORLD\n";
pthread_mutex_unlock(&mutex);//解锁
sleep(rand()%3);//如果这条语句没有,一旦这个线程抢到临界资源,就会大概率一直执行这个线程,其他线程很难抢到锁了。
}
}
void *thr2(void * agr)
{
while (1){
pthread_mutex_lock(&mutex);
cout<<"hello";
sleep(rand()%3);
cout<<"world\n";
pthread_mutex_unlock(&mutex);
sleep(rand()%3);
}
}
int main()
{
pthread_t tid[2];
pthread_create(&tid[0], NULL, thr1, NULL);
pthread_create(&tid[1], NULL, thr2, NULL);
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}
结果
读写锁
读写锁允许多个线程同时读,但读写操作、写写操作之间仍要相互等待,并且写操作优先级高,如果读操作和写操作同时在排队,下一次就会优先执行写操作。
用法和互斥锁差不多
程序举例如下:
#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int num=0;
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
using namespace std;
void *thr_write(void * agr)
{
while (1){
pthread_rwlock_wrlock(&rwlock);
num++;
cout<<"---"<<__FUNCTION__<<"---self---"<<pthread_self()<<"---num---"<<num<<endl;
usleep(2000);
pthread_rwlock_unlock(&rwlock);
usleep(4000);
}
return NULL;
}
void *thr_read(void * agr)
{
while (1){
pthread_rwlock_rdlock(&rwlock);
cout<<"---"<<__FUNCTION__<<"---self---"<<pthread_self()<<"---num---"<<num<<endl;
usleep(2000);
pthread_rwlock_unlock(&rwlock);
usleep(2000);
}
return NULL;
}
int main()
{
int n=8, i;
pthread_t tid[8];
for (i=0; i<5; i++){
pthread_create(&tid[i], NULL, thr_read, NULL);
}
for (; i<8; i++){
pthread_create(&tid[i], NULL, thr_write, NULL);
}
for (i=0; i<8; i++){
pthread_join(tid[i], NULL);
}
return 0;
}