Files
ST-OS/Practice_07/Producer_Consumer_TAS.c

55 lines
1.0 KiB
C

#include <stdio.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int lock = 0; //원자적 변수
int counter = 5;
int TestAndSet(atomic_int *target){
// atomic으로 비슷하게 흉내.
// 어셈블리어 수준의 원자적 표현이 없음
return atomic_exchange(target, 1);
}
void acquire_lock(atomic_int *lock){
while(TestAndSet(lock) == 1){
// 바쁜대기중...
}
}
void release_lock(atomic_int *lock){
atomic_store(lock, 0);
}
void* producer(void* arg){
for(int i = 0; i < 1000000; i++){
acquire_lock(&lock);
counter++;
release_lock(&lock);
}
return NULL;
}
void *consumer(void* arg){
for(int i = 0; i < 1000000; i++){
acquire_lock(&lock);
counter--;
release_lock(&lock);
}
return NULL;
}
int main(){
pthread_t t1, t2;
pthread_create(&t1, NULL, producer, NULL);
pthread_create(&t2, NULL, consumer, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("최종 Counter 값 : %d\n", counter);
return 0;
}