使用过程:
1,声明锁: pthread_mutex_t lock;
2,初始化锁:pthread_mutex_init(&lock,NULL);
3,在线程的方法函数中上锁和解锁:(成对出现)
pthread_mutex_lock(&lock);
pthread_mutex_unlock(&lock);
4,销毁锁:pthread_mutex_destroy(&lock);
代码示例:
#include
#include
#include
#include
pthread_mutex_t lock;//在全局区声明互斥锁
void *tick(void *arg)
{
static int num =10;
while(num>0){
pthread_mutex_lock(&lock);
if(num<=0)
{
pthread_mutex_unlock(&lock);
break;
}
num--;
sleep(1);
printf("线程%ld销售了一张票,还剩%d张\n",pthread_self(),num);
pthread_mutex_unlock(&lock);
}
}
int main(int argc,char const *argv[])
{
pthread_mutex_init(&lock,NULL);//初始化互斥锁
pthread_t p1,p2,p3,p4; //定义四个线程;共享此进程的数据
pthread_create(&p1,NULL,tick,NULL);
pthread_create(&p2,NULL,tick,NULL);
pthread_create(&p3,NULL,tick,NULL);
pthread_create(&p4,NULL,tick,NULL);//创建四个线程
pthread_join(p1,NULL);
pthread_join(p2,NULL);
pthread_join(p3,NULL);
pthread_join(p4,NULL);//等待四个线程结束
pthread_mutex_destroy(&lock);//销毁互斥锁
return 0;
}
条件变量:使用过程:
1,声明条件变量 pthread_cond_t cond;
2,初始化条件变量 pthread_cond_init(&cond,NULL);
3,在一对互斥锁中间:pthread_cond_wait(&cond,&lock);//会打开互斥锁,并且阻塞程序,–直到另一个信号函数pthread_cond_broadcast(&cond);被执行时解除阻塞.或者pthread_cond_signal(&cond)函数;
4,释放条件变量pthread_cond_destroy(&cond);
代码示例:生产者-消费者模型
#include
#include
#include
#include
#include
#include
pthread_mutex_t lock;//声明互斥锁
pthread_cond_t cond; //声明条件变量
int num = 0; //声明记录库存数量的变量
void *produce(void *argv)
{
while(1){
pthread_mutex_lock(&lock);
while(num >= 10)
{
printf("库存已满,线程%ld停止生产\n",pthread_self());
pthread_cond_wait(&cond,&lock);
}
num++;
printf("线程%ld生产了一个商品,当前库存数量为:%d\n",pthread_self(),num);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
sleep(1);
}
return NULL;
}
void *sale(void *argv)
{
while(1)
{
pthread_mutex_lock(&lock);
while(num <= 0)
{
printf("库存为0,线程%ld停止销售\n",pthread_self());
pthread_cond_wait(&cond,&lock);
}
num--;
printf("线程%ld销售了一个商品,当前库存数量为:%d\n",pthread_self(),num);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
int t = rand()%5;
sleep(t);
}
}
void closeThread(pthread_t ts[],int len) //声明释放线程的方法
{
for(int i = 0; i < len; i++)
{
pthread_join(ts[i],NULL);
}
}
int main(int argc, char const *argv[])
{
srand(time(NULL));
pthread_mutex_init(&lock,NULL);//初始化互斥锁
pthread_cond_init(&cond,NULL);//初始化条件变量
pthread_t ps[3];//声明生产者线程组
pthread_t ss[5];//声明销售者线程组
int i;
for(i = 0; i < 3; i++)
{
pthread_create(&ps[i],NULL,produce,NULL);//创建线程并执行
}
for(int i = 0; i < 5; i++)
{
pthread_create(&ps[i],NULL,sale,NULL);
}
int plen = sizeof(ps)/sizeof(pthread_t);
closeThread(ps,plen);//释放生产者线程
int slen = sizeof(ss)/sizeof(pthread_t);
closeThread(ss,slen);//释放消费者线程
pthread_mutex_destroy(&lock);//释放互斥锁
pthread_cond_destroy(&cond);//释放条件变量
return 0;
}