33 lines
754 B
C
33 lines
754 B
C
#include <stdio.h>
|
|
#include <pthread.h>
|
|
#include <semaphore.h>
|
|
#include <sys/semaphore.h>
|
|
|
|
int counter = 0; // shared resource
|
|
sem_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
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
int main() {
|
|
pthread_t t1, t2;
|
|
sem_init(&semaphore, 0, 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);
|
|
|
|
printf("Final Counter Value (with semaphores): %d\n", counter);
|
|
|
|
return 0;
|
|
}
|