【オペレーティングシステム】プロセス同期コードチェック

2089 ワード

/* Cosumer and Producer model(Incorrect) */

/* Producer */
int nextProduced;
while(true){
	while(count == n);
	buffer[in] = nextProduced;
	in = (in + 1) % BUFFER_SIZE;
	count++;
}

/* Consumer */
int nextConsumed;
while(true){
	while(count == 0);
	nextConsumed = buffer[out];
	out = (out + 1) % BUFFER_SIZE; 
	count--;
}


/* Peterson's solution */
do{
	flag[i] = true;
	turn = j;
	while(turn == j && flag[j] == true);
	//critical section
	flag[i] = false;
	//remainder section
}while(true);

/* TestAndSet solution*/
bool waiting[n];
bool lock;

do
{
	waiting[i] = true;
	key = true;
	while(waiting[i] && key){
		key = TestAndSet(&lock);
	}
	waiting[i] = false;

	// critical section

	j = (i+1) % n;
	while(j!=i && !waiting[j]){
		j = (j+1) % n;
	}
	if(j == i){
		lock = false;
	}
	else{
		waiting[j] = false;
	}

	// remainder section
} while (true);


/* Mutex implementation */
semaphore mutex;
do{
	waiting(mutex);
	// critical section
	signal(mutex);
	// remainder section
}while(true);


/* Semaphore implemantation */
typedef struct {
	int value;
	struct process* list;
} semaphore;

wait(semaphore* s){
	s->value--;
	if(s->value < 0){
		add this process to s->list
		block();
	}
}

signal(semaphore* s){
	s->value++;
	if(s->value <= 0){
		remove a process P from s->list
		wakeup(P);
	}
}

/* The bounded buffer problem: mutex solution*/
semaphore mutex = 1;
semaphore full = 0;
semaphore empty = n;

// Producer
do{
	wait(empty);
	wait(mutex);

	// add to buffer
	signal(mutex);
	signal(full);
}while(true);

// Consumer
do{
	wait(full);
	wait(mutex);

	// remove an item from buffer
	signal(mutex);
	signal(empty);
}while(true);


/* read write problem */
semaphore mutex, wrt;
int readcount;

// writer
do{
	wait(wrt);
	//writing is performed
	signal(wrt);
}while(true);

// reader
do{
	wait(mutex);
	readcount++;
	if(readcount == 1){
		wait(wrt);
	}
	signal(mutex);

	// reading is performed

	wait(mutex);
	readcount--;
	if(readcount == 0){
		signal(wrt);
	}
	signal(mutex);

}while(true);