多任务互斥与同步(互斥锁, 读写锁, 条件变量, 信号量, 命名信号量): 作业3

This commit is contained in:
flykhan 2023-08-22 23:34:57 +08:00
parent 0df47fc15c
commit 663a501a63
1 changed files with 42 additions and 0 deletions

42
day7/homework/h3.c Normal file
View File

@ -0,0 +1,42 @@
/*
, 线, 线线, 线,
*/
#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;
}