This commit is contained in:
2026-05-16 12:08:49 +08:00
parent f679b67969
commit 119f0e7b3a
16 changed files with 1114 additions and 0 deletions

46
AI-work/task62.c Normal file
View File

@@ -0,0 +1,46 @@
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
volatile long long counter = 0;
long long niters;
sem_t mutex;
void *thread_func(void *arg)
{
for (long long i = 0; i < niters; i++) {
sem_wait(&mutex);
counter++;
sem_post(&mutex);
}
return NULL;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "Usage: %s <niters>\n", argv[0]);
return 1;
}
niters = atoll(argv[1]);
sem_init(&mutex, 0, 1);
pthread_t t1, t2;
pthread_create(&t1, NULL, thread_func, NULL);
pthread_create(&t2, NULL, thread_func, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Expected: %lld, Got: %lld\n", 2 * niters, counter);
if (counter != 2 * niters) {
printf("ERROR: Race condition detected!\n");
} else {
printf("Correct! No race condition.\n");
}
sem_destroy(&mutex);
return 0;
}