Univ/Study
[OS] pthread.h 실행 명령어
Jay, Lee
2022. 5. 10. 15:29
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define ITER 1000
void *thread_increment(void * arg);
void *thread_decrement(void * arg);
int x;
sem_t s;
int main() {
pthread_t tid1, tid2;
sem_init(&s, 0, 1);
pthread_create(&tid1, NULL, thread_increment, NULL);
pthread_create(&tid2, NULL, thread_decrement, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
if (x != 0 ) printf("boom! counter=%d\n", x);
else printf("ok counter=%d\n", x);
sem_destroy(&s);
}
void * thread_increment(void *arg) {
int i, val;
for (i = 0; i < ITER; i++) {
sem_wait(&s);
val = x;
printf("%u: %d\n", (unsigned int) pthread_self(), val);
x = val + 1;
sem_post(&s);
}
return NULL;
}
void * thread_decrement(void *arg) {
int i, val;
for (i = 0; i < ITER; i++) {
sem_wait(&s);
val = x;
printf("%u: %d\n", (unsigned int) pthread_self(), val);
x = val - 1;
sem_post(&s);
}
return NULL;
}
gcc thread.c -lpthread 해줘야한다.