Software-based Solutions for Critical section problem

Peterson’s Algorithm

while (true)
{
	flag[i] = true;
	turn = j;

	while (flag[j] && turn == j) // entry section
		;

	/* critical section */

	flag[i] = false; // exit section

	/* remainder section */
}

ij 두 개의 프로세스 존재

ij 두 개의 프로세스가 동시에 Critical section에 진입 불가능

<간단하게 구현>

#include <stdio.h>
#include <pthread.h>

#define true 1
#define false 0

int sum = 0;

int turn;
int flag[2];

int main()
{
	pthread_t tid1, tid2;
	pthread_create(&tid1, NULL, producer, NULL);
	pthread_create(&tid2, NULL, consumer, NULL);
	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);
	printf("sum = %d\\n", sum);
}

<생산자 코드>

void* producer(void* param)
{
	for (int k = 0; k < 10000; ++k)
	{
		/* entry section */
		flag[0] = true;
		turn = 1;

		while (flag[1] && turn == 1)
			;

		/* critical section */
		sum++;

		/* exit section */
		flag[0] = false;

		/* remainder section */
	}
	pthread_exit(0);
}

<소비자 코드>

void* consumer(void* param)
{
	for (int k = 0; k < 10000; ++k)
	{
		/* entry section */
		flag[1] = true;
		turn = 0;

		while (flag[0] && turn == 0)
			;

		/* critical section */
		sum--;

		/* exit section */
		flag[1] = false;

		/* remainder section */
	}
	pthread_exit(0);
}