1. Thread Libraries
Thread library : 프로그래머가 스레드를 쉽게 생성하고 조작할 수 있도록 도와주는 소프트웨어 라이브러리
Examples
- POSIX Pthreads : POSIX 호환 운영체제에서 멀티스레드 애플리케이션을 작성하기 위한 API
- Win32 threads
- Java threads
2. POSIX Pthreads
POSIX Threads (pthread)의 API 함수들
1. 스레드를 생성하는 함수
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
- thread는 스레드 식별자를 저장할 변수의 포인터
- attr은 스레드 속성을 지정하는 변수의 포인터 (null 값을 보내면 디폴트 사용가능)
- start_routine은 스레드가 실행할 함수
- arg는 start_routine에 전달할 인자
2. 스레드 속성 변수인 attr을 기본값으로 초기화하는 함수
int pthread_attr_init(pthread_attr_t *attr);
3. 스레드 th가 종료될 때까지 대기하는 함수 (child 쓰레드 기다림)
int pthread_join(pthread_t th, void **thread_return);
4. 스레드를 종료하는 함수
void pthread_exit(void *retval);
예시코드
#include <pthread.h>
#include <stdio.h>
int sum = 0; /* this data is shared by the thread(s) */
void *runner(void *param); /* the thread */
int main (int argc, char *argv[])
{
pthread_t tid = 0; /* the thread identifier */
pthread_attr_t attr; /* set of thread attributes */
if (argc < 2 ) {
fprintf(stderr,“usage: a.out <integer>\n”);
exit(0);
}
if (atoi(argv[1]) < 0) {
fprintf(stderr,“%d must be <= 0\n”,atoi(argv[1]));
exit(0);
}
/* get the default attributes */
pthread_attr_init(&attr);
/* create the thread */
pthread_create(&tid,&attr,runner,argv[1]);
/* now wait for the thread to exit */
pthread_join(tid,NULL); //얘가없으면 바로 sum 출력되서 이상한 값 출력
printf(“sum = %d\n”,sum);
return 0;
}
/* The thread will begin control in this function */
void *runner(void *param)
{
int upper = atoi(param); // atoi string -> int로 바꿔줌
int i = 0;
sum = 0;
if (upper > 0) {
for (i = 1; i <= upper ; i++)
sum += i;
}
return NULL;
}
실행방법
gcc th- .c -pthread
.a/out.c
3. Windows Threads
/*Create*/
HANDLE WINAPI CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);
/* Wait */
DWORD WINAPI WaitForSingleObject(
HANDLE hHandle,
DWORD dwMilliseconds // time-out interval
);
/* Close (deallocate) handle */
BOOL CloseHandle(LPDWORD lpThreadId);
4. Java Threads
Java 스레드는 JVM에 의해 관리
일반적으로 기본 OS에서 제공하는 스레드 모델을 사용하여 구현
Java 스레드는 다음을 통해 생성
- Extending Thread class
- Implementing the Runnable interface
public interface Runnable
{
public adstract void run();
}
Java Thread using Thread Class
/* Extending Thread class */
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
/* Launching thread */
PrimeThread p = new PrimeThread(143);
p.start();
Java Thread using Running Interface
/* Extending Thread class */
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
. . .
}
}
/* Launching thread */
PrimeRun p = new PrimeRun(143);
new Thread(p).start();
5. Implicit Threading
Implicit threading : 프로그래머가 쓰레드 생성과 관리를 직접하지 않고, 컴파일러나 런타임 라이브러리가 자동으로 처리하는 쓰레드 생성 기술
Three methods explored
- Thread Pools
- OpenMP
- Grand Central Dispatch
Thread Pools : 여러 개의 쓰레드를 미리 만들어 놓고, 필요할 때마다 작업을 할당하여 사용하는 방식
Thread Pools의 장점
- 이미 존재하는 스레드로 요청을 처리하는 것이 새로운 스레드를 생성하는 것보다 조금 더 빠르다
- 애플리케이션의 스레드 수를 풀의 크기에 바인딩하여 구현할 수 있으므로 자원의 효율성이 높다
- 작업 수행과 작업 생성 기능을 분리함으로써 작업을 실행하는 다양한 전략을 적용할 수 있다. (작업을 주기적으로 실행)
OpenMP : 공유 메모리 환경에서 병렬 프로그래밍을 지원하는 방법
C, C++, FORTRAN에서 사용 가능한 컴파일러 지시어와 API로 구성되어 있다.
코어 또는 H/W 스레드 수만큼 스레드 생성
#pragma omp parallel // each runs the statement
printf(“Hello, World!\n”);
루프를 병렬로 실행
#pragma omp parallel for // unroll loop over cores
for(i=0;i<N;i++) {
c[i] = a[i] + b[i];
}
'Study > 운영체제' 카테고리의 다른 글
4. Threads - Threading issues (0) | 2023.04.12 |
---|---|
4. Threads - Multithreading models (0) | 2023.04.12 |
4. Threads - Overview (0) | 2023.04.12 |
3. Processes - Example of IPC system (0) | 2023.04.11 |
3. Processes - Inter-process communication (0) | 2023.04.11 |