binary semaphore code
This commit is contained in:
@@ -6,6 +6,7 @@ SRCS := dining_philosophers_deadlock.c \
|
|||||||
dining_philosophers_no_deadlock.c \
|
dining_philosophers_no_deadlock.c \
|
||||||
dining_philosophers_no_deadlock_print.c \
|
dining_philosophers_no_deadlock_print.c \
|
||||||
join.c \
|
join.c \
|
||||||
|
binary.c \
|
||||||
zemaphore.c
|
zemaphore.c
|
||||||
|
|
||||||
OBJS := ${SRCS:c=o}
|
OBJS := ${SRCS:c=o}
|
||||||
|
|||||||
@@ -6,8 +6,23 @@ using semaphores, found in `join.c`.
|
|||||||
|
|
||||||
Run `make` to build the code; run `join` to test it. Fun!
|
Run `make` to build the code; run `join` to test it. Fun!
|
||||||
|
|
||||||
|
```sh
|
||||||
|
prompt> make
|
||||||
|
prompt> ./join
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
# Binary Semaphores (Locks)
|
||||||
|
|
||||||
|
Simple example of semaphores as locks (binary semaphores).
|
||||||
|
Code in `binary.c`.
|
||||||
|
|
||||||
|
Run `make` to build the code; run `binary` to test it. Fun!
|
||||||
|
|
||||||
|
```sh
|
||||||
|
prompt> make
|
||||||
|
prompt> ./binary
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
# Dining Philosophers
|
# Dining Philosophers
|
||||||
|
|||||||
32
threads-sema/binary.c
Normal file
32
threads-sema/binary.c
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <pthread.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#include "common.h"
|
||||||
|
#include "common_threads.h"
|
||||||
|
|
||||||
|
sem_t mutex;
|
||||||
|
volatile int counter = 0;
|
||||||
|
|
||||||
|
void *child(void *arg) {
|
||||||
|
int i;
|
||||||
|
for (i = 0; i < 10000000; i++) {
|
||||||
|
Sem_wait(&mutex);
|
||||||
|
counter++;
|
||||||
|
Sem_post(&mutex);
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
Sem_init(&mutex, 1);
|
||||||
|
pthread_t c1, c2;
|
||||||
|
Pthread_create(&c1, NULL, child, NULL);
|
||||||
|
Pthread_create(&c2, NULL, child, NULL);
|
||||||
|
Pthread_join(c1, NULL);
|
||||||
|
Pthread_join(c2, NULL);
|
||||||
|
printf("result: %d\n", counter);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
Reference in New Issue
Block a user