##设置一个进程,有3个线程,然后每个线程都打印1~10,但要求使用互斥锁,让3个线程按顺序执行,不要同时执行,当线程的数值打印到5时候,让其他还没有/打印的线程先运行,当所有的数值都打印到5时,再继续运行线程,
###题目如上
马上贴上代码
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t m;
pthread_cond_t k;
void *f(void *arg)
{
char *s = (char *)arg;
//加锁
pthread_mutex_lock(&m);
printf("%s get cond success\n",s);
int i=0;
while(i++<10)
{
printf("%s: =%d\n",s,i);
sleep(1);
//printf(" bijao%d\n",strcmp(s,"C"));
if( i == 5 && strcmp(s,"C") == 0)
{
pthread_cond_wait(&k,&m);
//pthread_cond_signal(&k);
}
if( i == 5 && strcmp(s,"B") == 0 )
{
printf("B stop\n");
pthread_cond_wait(&k,&m);
//pthread_cond_signal(&k);
}
if( i == 5 && strcmp(s,"A") == 0 )
{
pthread_cond_broadcast(&k);
}
}
pthread_mutex_unlock(&m);
}
int main()
{
//初始化互斥锁
pthread_mutex_init(&m,NULL);
//初始化条件变量
pthread_cond_init(&k,NULL);
pthread_t tid1,tid2,tid3;
pthread_create(&tid2,NULL,f,"A");
pthread_create(&tid3,NULL,f,"B");
pthread_create(&tid1,NULL,f,"C");
//pthread_cond_signal(&k);
//pthread_cond_broadcast(&k);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
//销毁条件变量
pthread_cond_destroy(&k);
//销毁互斥锁
pthread_mutex_destroy(&m);
return 0;
}
运行现象:
提醒,代码运行环境为ubuntu12.04,运行时请加上-pthread,否则会出翔undfine的error
1.main中我依次create几个线程(参数不一样),(根据最后一个参数,将线程依次命名为a,b,c),main运行时,依次创建了线程,然后都被lock,最后创建的c线程最先拿到资源,然后开始运行代码,当i = = 5 的时候,f()运行到if(),然后开始睡眠,被lock的进程开始拿到资源,然后运行代码,等b运行并睡眠后,a开始运行.运行到i==5时,全部唤醒(pthread_cond_broadcast(&k)),(pthread_cond_signal(&k);是唤醒一个),然后a运行完之后,其他的线程拿到资源,开始运行,这就是程序的所有分析过程