死锁
假如我有两个以上的锁,我线程1已经获得锁1,想要获得锁2,而我线程2已经获得锁2,想要获得锁1,现在双方都获取不到自己想要的东西,就会一直等待,这就是死锁。
线程同步
pthread_cond_t创建条件变量
pthread_cond_t cond; // 定义一个条件变量,是一个结构体
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
brief:初始化条件变量(条件变量是利用全局变量进行同步的机制)
param:第一个参数是要初始化的条件变量,第二个参数,NULL
return:成功返回0 ,
pthread_cond_wait等待条件变量
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
brief:第一次调用会自动释放锁堵塞在这里等待被唤醒,被唤醒后自动上锁
param:第一个参数,条件变量的地址,第二个参数,锁的地址(条件变量必须配合互斥锁使用)
return:成功返回0
pthread_cond_signal唤醒线程
int pthread_cond_signal(pthread_cond_t *cond);
brief:唤醒阻塞的线程,唤醒的线程从堵塞处开始执行
param:条件变量的地址
return:成功返回0
pthread_cond_destroy销毁条件变量
int pthread_cond_destroy(pthread_cond_t *cond);
brief:销毁条件变量
param:需要销毁的条件变量的地址
return:成功返回0
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
int data = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void * handler1(void * argc)
{
//while(1)//while里面可以不用写解锁,因为再次调用wait的时候,就已经释放锁了
// { //如果不用while,则必须解锁,不然线程1退出过后,线程2 获取不到锁就会堵塞
pthread_cond_wait(&cond,&mutex);
printf("t1:%d\n",data);
data = 0;
printf("没错就是这样\n");
// }
pthread_mutex_unlock(&mutex);
}
void * handler2(void * argc)
{
while(1)
{
pthread_mutex_lock(&mutex);
printf("t2:%d\n",data);
data++;
if(data == 3)
{
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void main()
{
pthread_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_create(&t1,NULL,handler1,NULL);
pthread_create(&t2,NULL,handler2,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
我们可以编一个程序来记录我们跑10次
#include <stdio.h>
void main(int argc,char **argv)
{
int time = atoi(argv[1]);
int i;
for(i = 0;i < time;++i)
{
system("./pp");
}
}
编译测试程序后输入./a.out 10 >>test & 10是运行十次的意思 &是后台运行 运行完后,打开test可以看到10次运行效果都写入到文件里了