From 755d43d40760e8cd489e31d178212339e9aa763c Mon Sep 17 00:00:00 2001 From: foxliver Date: Thu, 25 Sep 2025 16:44:51 +0900 Subject: [PATCH] Producer Consumer TAS Sample code --- Practice_07/Producer_Consumer_TAS.c | 55 +++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Practice_07/Producer_Consumer_TAS.c diff --git a/Practice_07/Producer_Consumer_TAS.c b/Practice_07/Producer_Consumer_TAS.c new file mode 100644 index 0000000..6dc9c01 --- /dev/null +++ b/Practice_07/Producer_Consumer_TAS.c @@ -0,0 +1,55 @@ +#include +#include +#include + +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; +} \ No newline at end of file