58 lines
1.2 KiB
C
58 lines
1.2 KiB
C
#include <stdio.h>
|
|
#include <pthread.h>
|
|
#include <stdlib.h>
|
|
#include <semaphore.h>
|
|
//设置办理业务的人数
|
|
int num = 5;
|
|
//创建信号量
|
|
sem_t sem;
|
|
//模拟办理业务的过程
|
|
void *get_service(void *arg)
|
|
{
|
|
int id = *((int *)arg);
|
|
//信号量成功“减 1”后才能继续执行
|
|
if (sem_wait(&sem) == 0)
|
|
{
|
|
printf("---customer%d 正在办理业务\n", id);
|
|
sleep(2);
|
|
printf("---customer%d 已办完业务\n", id);
|
|
//信号量“加 1”
|
|
sem_post(&sem);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
int flag, i, j;
|
|
//创建 5 个线程代表 5 个人
|
|
pthread_t customer[5];
|
|
//初始化信号量
|
|
sem_init(&sem, 0, 2);
|
|
for (i = 0; i < num; i++)
|
|
{
|
|
flag = pthread_create(&customer[i], NULL, get_service, &i);
|
|
if (flag != 0)
|
|
{
|
|
printf("线程创建失败!\n");
|
|
return 0;
|
|
}
|
|
else
|
|
{
|
|
printf("customer%d 来办理业务\n", i);
|
|
}
|
|
sleep(1);
|
|
}
|
|
|
|
for (j = 0; j < num; j++)
|
|
{
|
|
flag = pthread_join(customer[j], NULL);
|
|
if (flag != 0)
|
|
{
|
|
printf("tid=%d 等待失败!", customer[i]);
|
|
return 0;
|
|
}
|
|
}
|
|
sem_destroy(&sem);
|
|
return 0;
|
|
} |