qfedu-linux-advanced-level/day7/homework/h3.c

43 lines
910 B
C
Raw Permalink Normal View History

/*
, 线, 线线, 线,
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
sem_t sem;
int number = 0;
void *
addfun(void *data)
{
sem_wait(&sem);
number++;
printf("%ld 线程时, number = %d\n", pthread_self(), number);
sem_post(&sem);
}
int main(int argc, char const *argv[])
{
sem_init(&sem, 0, 1);
printf("开始的 number = %d\n", number);
pthread_t t[5];
for (int i = 0; i < 5; i++)
{
pthread_create(&t[i], NULL, addfun, NULL);
}
for (int i = 0; i < 5; i++)
{
pthread_join(t[i], NULL);
}
printf("现在的 number = %d\n", number);
sem_destroy(&sem); // 销毁信号量
return 0;
}