OS - threads & concurrency

Bomin Seo·2022년 8월 5일
0
post-custom-banner

Process

Process is heavy-weight

  • address space, OS resource, Hardware execution state 등 많은 정보를 담고 있다
  • 모든 data structure를 할당하고 초기화해야하기 때문에 프로세스를 새로 만드는 것은 비싸다
  • inter-process communication은 OS를 거쳐야하기 때문에 비싸다

thread (process의 단점을 보완하기 위해 고안)

  • SunOS에서 개념 제시, lightweight process

  • 실행 path만을 더 만든다는 개념을 사용한다.

Single-threaded process

void func1(void *p) { … }
void func2(void *p) { … }
main() 
{
	func1(…);
	func2(…);
	…
}

Multithreaded process

void func1(void *p) { … }
void func2(void *p) { … }
main() 
{
	thread_create(func1, …);
	thread_create(func2, …);
	…
}

  • Code, static data, heap를 공유하며 실행되고 있는 상황을 저장하는 register와 thread의 함수 호출을 저장할 stack, stack pointer, PC는 thread별로 가진다.

Concurrent server

webserver example

  • multiprocess model
While (1) {
	int sock = accept();
	if ((pid = fork()) == 0) {
		/* Handle client request */
	} else {
		/* Close socket */
	}
}
  • multithread model
webserver ()
{
	While (1) {
		int sock = accept();
		thread_fork (handle_request, sock);
	}
}
handle_request (int sock)
{
	/* Process request */
	close (sock);
}

Multicore Programming

Concurrent execution on a single-core system

Parallel execution on a multicore system

Data vs. Task parallelism

Multithreading Model

Many-to-One (사장된 model)

One-to-One (Windows에서 사용하는 Model)

Many-to-many (m : n 방식/Solaris에서 사용)

Two-Level (Many-to-Many + One-to-One)


Pthreads (POSIX threads)

pthread_join : tid가 끝나길 기다리는 명령어

POSIX

  • IEEE에서 UNIX system call을 표준화하였다

Thread creation/termination

int pthread_create (pthread_t *tid,  pthread_attr_t *attr, void *(start_routine)(void *), void *arg);

void pthread_exit (void *retval); 

int pthread_join (pthread_t tid,  void **thread_return); 

Mutexes

int pthread_mutex_init (pthread_mutex_t *mutex,  const pthread_mutexattr_t *mattr);

int pthread_mutex_destroy  (pthread_mutex_t *mutex); 

int pthread_mutex_lock  (pthread_mutex_t *mutex); 

int pthread_mutex_unlock (pthread_mutex_t *mutex); 

Condition variables

int pthread_cond_init (pthread_cond_t *cond,  const pthread_condattr_t *cattr);

int pthread_cond_destroy  (pthread_cond_t *cond); 

int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex); 

int pthread_cond_signal (pthread_cond_t *cond); 

int pthread_cond_broadcast (pthread_cond_t *cond); 

Windows Threads

Thread creation/termination

HANDLE CreateThread (lpThreadAttributes, dwStackSize,  lpStartAddress, lpParameter,  dwCreationFlags, lpThreadId);

void ExitThread (dwExitCode); 

Java Threads

Thread creation/termination

Create a new class derived from Thread class Override run() method

Create a new class that implements the runnable interface
profile
KHU, SWCON
post-custom-banner

0개의 댓글