2026-05-14 09:27:48 +08:00
|
|
|
#include <pthread.h>
|
|
|
|
|
#include <time.h>
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
#include <unistd.h>
|
2026-05-14 11:07:54 +08:00
|
|
|
#include <semaphore.h>
|
2026-05-14 09:27:48 +08:00
|
|
|
|
2026-05-16 21:52:40 +08:00
|
|
|
void *increase(void *vargp);
|
|
|
|
|
void *decrease(void *vargp);
|
2026-05-14 09:27:48 +08:00
|
|
|
int cnt = 0;
|
|
|
|
|
sem_t mutex;
|
|
|
|
|
|
|
|
|
|
int main(int argc, char **argv)
|
|
|
|
|
{
|
|
|
|
|
unsigned int niters;
|
|
|
|
|
pthread_t t1,t2;
|
2026-05-16 21:52:40 +08:00
|
|
|
|
2026-05-14 09:27:48 +08:00
|
|
|
if (argc != 2)
|
|
|
|
|
{
|
|
|
|
|
printf("Usage: %s <niters>\n", argv[0]);
|
|
|
|
|
exit(2);
|
|
|
|
|
}
|
|
|
|
|
niters = atoll(argv[1]);
|
2026-05-16 21:52:40 +08:00
|
|
|
|
2026-05-14 09:27:48 +08:00
|
|
|
sem_init(&mutex, 0, 1);
|
2026-05-16 21:52:40 +08:00
|
|
|
pthread_create(&t1,NULL,increase,(void *)niters);
|
|
|
|
|
pthread_create(&t2,NULL,decrease,(void *)niters);
|
2026-05-14 09:27:48 +08:00
|
|
|
pthread_join(t1,NULL);
|
|
|
|
|
pthread_join(t2,NULL);
|
2026-05-16 21:52:40 +08:00
|
|
|
|
2026-05-14 09:27:48 +08:00
|
|
|
if (cnt != 0)
|
|
|
|
|
{
|
|
|
|
|
printf("Error! cnt=%d\n", cnt);
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
printf("Correct! cnt=%d\n", cnt);
|
|
|
|
|
}
|
|
|
|
|
sem_destroy(&mutex);
|
|
|
|
|
exit(0);
|
2026-05-16 21:52:40 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void *increase(void *vargp)
|
|
|
|
|
{
|
|
|
|
|
unsigned i ,niters = (unsigned int)vargp;
|
|
|
|
|
for ( i = 0; i < niters; i++)
|
|
|
|
|
{
|
|
|
|
|
sem_wait(&mutex);
|
|
|
|
|
cnt++;
|
|
|
|
|
sem_post(&mutex);
|
|
|
|
|
}
|
|
|
|
|
return NULL;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void *decrease(void *vargp)
|
|
|
|
|
{
|
|
|
|
|
unsigned i, niters = (unsigned int)vargp;
|
|
|
|
|
for ( i = 0; i < niters; i++)
|
|
|
|
|
{
|
|
|
|
|
sem_wait(&mutex);
|
|
|
|
|
cnt--;
|
|
|
|
|
sem_post(&mutex);
|
|
|
|
|
}
|
|
|
|
|
return NULL;
|
2026-05-14 09:27:48 +08:00
|
|
|
}
|