题目
请使用互斥锁 和 信号量分别实现5个线程之间的同步
代码:信号量实现
void* task1(void* arg);
void* task2(void* arg);
void* task3(void* arg);
void* task4(void* arg);
void* task5(void* arg);
sem_t sem[5]; //信号量变量
int main(int argc, const char *argv[])
{
//信号量初始化
for(int i=0;i<5;i++)
{
sem_init(&sem[i],0,0);//初始化信号量数量
}
sem_post(&sem[0]);
//线程初始化
pthread_t id[4];
pthread_create(&id[0],0,task1,NULL);
pthread_create(&id[1],0,task2,NULL);
pthread_create(&id[2],0,task3,NULL);
pthread_create(&id[3],0,task4,NULL);
pthread_detach(id[0]);
pthread_detach(id[1]);
pthread_detach(id[2]);
pthread_detach(id[3]);
while(1)
{
task5(NULL);
}
return 0;
}
void* task1(void* arg)
{
while(1)
{
sem_wait(&sem[0]); //获取信号量0
printf("报数:1\n");
sleep(1);
sem_post(&sem[1]); //释放信号量1
}
}
void* task2(void* arg)
{
while(1)
{
sem_wait(&sem[1]); //获取信号量0
printf("报数:2\n");
sleep(1);
sem_post(&sem[2]); //释放信号量1
}
}
void* task3(void* arg)
{
while(1)
{
sem_wait(&sem[2]); //获取信号量0
printf("报数:3\n");
sleep(1);
sem_post(&sem[3]); //释放信号量1
}
}
void* task4(void* arg)
{
while(1)
{
sem_wait(&sem[3]); //获取信号量0
printf("报数:4\n");
sleep(1);
sem_post(&sem[4]); //释放信号量1
}
}
void* task5(void* arg)
{
while(1)
{
sem_wait(&sem[4]); //获取信号量0
printf("报数:5\n\n");
sleep(1);
sem_post(&sem[0]); //释放信号量1
}
}
效果
代码:互斥锁实现
void* task1(void* arg);
void* task2(void* arg);
void* task3(void* arg);
void* task4(void* arg);
void* task5(void* arg);
pthread_mutex_t mutex[5]; //互斥锁变量
int main(int argc, const char *argv[])
{
//互斥锁初始化
pthread_mutexattr_t mutex_attr; //锁属性
pthread_mutexattr_init(&mutex_attr); //锁属性初始化
for(int i=0;i<5;i++)
{
pthread_mutex_init(&mutex[i],&mutex_attr); //默认锁
pthread_mutex_lock(&mutex[i]); //上锁
}
pthread_mutex_unlock(&mutex[0]); //解锁0
//线程初始化
pthread_t id[4];
pthread_create(&id[0],0,task1,NULL);
pthread_create(&id[1],0,task2,NULL);
pthread_create(&id[2],0,task3,NULL);
pthread_create(&id[3],0,task4,NULL);
pthread_detach(id[0]);
pthread_detach(id[1]);
pthread_detach(id[2]);
pthread_detach(id[3]);
while(1)
{
task5(NULL);
}
return 0;
}
void* task1(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex[0]); //上锁0
printf("报数:1\n");
sleep(1);
pthread_mutex_unlock(&mutex[1]); //开锁1
}
}
void* task2(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex[1]); //上锁0
printf("报数:2\n");
sleep(1);
pthread_mutex_unlock(&mutex[2]); //开锁1
}
}
void* task3(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex[2]); //上锁2
printf("报数:3\n");
sleep(1);
pthread_mutex_unlock(&mutex[3]); //开锁3
}
}
void* task4(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex[3]); //上锁3
printf("报数:4\n");
sleep(1);
pthread_mutex_unlock(&mutex[4]); //开锁4
}
}
void* task5(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex[4]); //上锁4
printf("报数:5\n\n");
sleep(1);
pthread_mutex_unlock(&mutex[0]); //开锁0
}
}
效果