1、互斥锁
锁是一种很形象的说法:就像一个房间只能住一个人,任何人进去之后就把门锁上了,其他人都不可以进去,知道进去的人重新解锁,既是释放了这个锁资源为止。对于互斥锁的操作无非就是:定义互斥锁变量,初始化,加锁,解锁,销毁。
互斥锁使用与一对一情况之下,任何情况下都是只有一条线程访问共享资源
2、例子
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
pthread_mutex_t lock; //定义一个互斥锁变量
void Output(const char *string)
{
const char *ponit = string;
while(*ponit != '\0')
{
fprintf(stderr, "%c", *ponit);
ponit++;
usleep(100);
}
}
void *routine(void *arg)
{
pthread_mutex_lock(&lock); //在访问资源之前,加锁
Output((char *)arg);
pthread_mutex_unlock(&lock); 在访问资源完了,解锁
pthread_exit(NULL);
}
int main(int argc, void *argv[])
{
pthread_mutex_init(&lock, NULL); //任何互斥锁使用之前都要初始化
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, routine, "1111111111");
pthread_create(&tid2, NULL, routine, "2222222222");
pthread_join(tid1, NULL); //阻塞等待子线程tid1退出(非分离线程才可使用此函数)
pthread_join(tid2, NULL); //阻塞等待子线程tid2退出
pthread_mutex_destroy(&lock); //销毁互斥锁
exit(0);
}
3、读写锁
互斥锁和读写锁基本是一样的,只是在加锁时区分 “读锁” 还是 “写锁”
加读锁(可以重复加),加写锁(一次只能一个),多个线程都加了读锁,这多个线程可以同时访问读操作共享资源
4、读写锁例子
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
pthread_rwlock_t lock; //定义一个读写锁变量
int global = 0;
void *routine1(void *arg)
{
pthread_rwlock_wrlock(&lock); //在写访问资源之前,加锁
global++;
fprintf(stderr, "I am %s! global:%d\n", (char *)arg, global);
pthread_rwlock_unlock(&lock); //在写访问资源完了,解锁
pthread_exit(NULL);
}
void *routine2(void *arg)
{
pthread_rwlock_wrlock(&lock); //在写访问资源之前,加锁
global = 100;
fprintf(stderr,"I am %s! global:%d\n", (char *)arg, global);
pthread_rwlock_unlock(&lock); //在写访问资源完了,解锁
pthread_exit(NULL);
}
void *routine3(void *arg)
{
pthread_rwlock_rdlock(&lock); //在读访问资源之前,加锁
fprintf(stderr, "I am %s! global:%d\n", (char *)arg, global);
pthread_rwlock_unlock(&lock); //在读访问资源完了,解锁
pthread_exit(NULL);
}
int main(int argc, void *argv[])
{
pthread_rwlock_init(&lock, NULL); //任何互斥锁使用之前都要初始化
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, routine1, "thread11");
pthread_create(&tid2, NULL, routine2, "thread22");
pthread_create(&tid3, NULL, routine3, "thread33");
pthread_join(tid1, NULL); //阻塞等待子线程tid1退出
pthread_join(tid2, NULL); //阻塞等待子线程tid2退出
pthread_join(tid3, NULL); //阻塞等待子线程tid2退出
pthread_rwlock_destroy(&lock); //销毁读写锁
exit(0);
}