extended code to advanced input functionality

This commit is contained in:
hello 2025-02-09 03:33:42 +05:30
parent 58cf91a06d
commit 0fc6c74996
8 changed files with 34 additions and 27 deletions

View file

@ -1,32 +1,33 @@
#include <stdatomic.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/semaphore.h>
#include <dispatch/dispatch.h>
int counter = 0; // shared resource
sem_t semaphore; // semaphore declaration
atomic_int counter = 0; // shared resource
dispatch_semaphore_t semaphore; // semaphore declaration
void* increment(void* arg) {
for (int i = 0; i < 100000; i++) {
sem_wait(&semaphore); // lock
counter++; // critical section
sem_post(&semaphore); // unlock
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // lock
atomic_fetch_add(&counter, 1); // critical section
dispatch_semaphore_signal(semaphore); // unlock
}
return NULL;
}
int main() {
pthread_t t1, t2;
sem_init(&semaphore, 0, 1); // initialize semaphore with value 1
semaphore = dispatch_semaphore_create(1); // initialize semaphore with value 1
pthread_create(&t1, NULL, increment, NULL);
pthread_create(&t2, NULL, increment, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
sem_destroy(&semaphore);
dispatch_release(semaphore);
printf("Final Counter Value (with semaphores): %d\n", counter);
printf("Final Counter Value (with semaphores): %d\n", atomic_load(&counter));
return 0;
}