'동기화'에 해당되는 글 3건

  1. 2010.01.08 Semaphore 이용환 Download 완료 확인
  2. 2010.01.08 식사하는 철학자 동기화
  3. 2010.01.08 Reader / Writer 동기화

Semaphore 이용환 Download 완료 확인

CS/Common 2010. 1. 8. 07:10
원문 : Stanford iTunesU Programming Paradigm 17강

int DownloadSingleFile(const char* server, const char* path);
int DownloadAllFiles(const char* server, const char* files[], int n)
{
	int totalBytes = 0;

	Semaphore lock = 1;
	Semaphore childrenDone = 0;

	for (int i=0; i < n; ++i)
	{
		ThreadNew("DownloadSingleFile", DownloadSingleFile, 4, server, files[i], &
		totalBytes, lock, childrenDone);
	}
	for (int i=0; i < n; ++i)
	{
		// wait return.
		SemaphoreWait(childrenDone);
	}

	return totalBytes;
}

void DownloadHelper(const char* server, const char* path, 
	int* returnButes, Semaphore lock, Semaphore parentToSignal)
{
	int bytesDownloaded = DownloadSingleFile(server, path);
	SemaphoreWait(lock);
	*numBytes += bytesDownloaded;
	SemaphoreSignal(lock);
	SemaphoreSignal(parentToSignal);
}
:

식사하는 철학자 동기화

CS/Common 2010. 1. 8. 06:48
원문 : Stanford iTunesU Programming Paradigm 17강

Semaphore forks[5] = {1, 1, 1, 1, 1}
Semaphore numAllowedToEat(4); // 최소한 한명은 Idle. DeadLock 피함.

void Philosopher(int id)
{
	for (int i=0; i < 3; ++i) 
	{
		Think();
		SemaphoreWait( numAllowedToEat );
		SemaphoreWait( forks[ id ] );
		SemaphoreWait( forks[ (i+1)%5 ] );
		Eat();
		SemaphoreSignal( forks[ id ] );
		SemaphoreSignal( forks[ (id+1)%5 ] );
		SemaphoreSignal( numAllowedToEat );
	}
}

학부때 OS 시간에는 뭔가 엄청 복잡하고 어려웠는데... 왜이렇게 간단하지...? ;;;
:

Reader / Writer 동기화

CS/Common 2010. 1. 8. 05:45
원문 : Stanford iTunesU Programming Paradigm 16강

버퍼에서 Read 전에 Write 금지.
Write 되지 않은 버퍼 Read 하지 않기.
char buffer[8];
Semaphore emptyBuffers(8);
Semaphore fullBuffers(0);

int main()
{
	ThreadNew("Writer", Writer, 0);
	ThreadNew("Reader", Reader, 0);
	RunAllThread();
}

void Writer()
{
	for (int i=0; i < 40; ++i)
	{
		char c = PrepareRandomChar();
		SemaphoreWait(emptyBuffers);
		buffer[ i%f ] = c;
		SemaphoreSignal(fullBuffers);
	}
}

void Reader()
{
	for (int i=0; i < 40; ++i)
	{
		SemaphoreWait(fullBuffers);
		char c = buffer[ i%f ];
		ProcessChar(c);
		SemaphoreSignal(emptyBuffers);
	}
}
: