thread : Used to interact with this thread.
attr : Used to specify any attributes this thread might have.
- Stack size, Scheduling priority,...
start_routine : the function this thread start running in
arg : the argument to be passed to the function (start routine)
- a void pointer allows us to pass in any type of argument
만약 start_routine 대신에 다른 type argument가 필요하다면 declaration은 위와 같을 것이다.
thread : 기다려야 하는 thread
value_ptr : return value의 pointer.
- pthread_join() routine이 value를 바꾸기 때문에, value에 대해서 pointer값을 넣어줘야 한다.
#include <stdio.h>
#include <assert.h>
#include <pthread.h>
typedef struct Myarg_t{
int a;
int b;
} myarg_t;
void *mythread(void* arg){
myarg_t *m = (myarg_t *) arg;
printf("%d %d\n", m->a, m->b);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t p1;
int rc;
myarg_t args;
args.a = 10;
args.b = 20;
rc = pthread_create(&p1, NULL, mythread, &args);
assert(rc == 0);
pthread_join(p1, NULL);
return 0;
}
Dangerous code
void *mythread(void* arg){
myarg_t *m = (myarg_t *) arg;
printf("%d %d\n", m->a, m->b);
myret_t r;
r.x = 1;
r.y = 2;
return (void *)&r;
}
해당 코드를 실행하면 segementation fault가 뜬다
현재 mythread 함수에서 local 변수로 myret_t 타입의 r이 선언되었는데 mythread 함수에서만 r의 life가 보장된다.
즉, 참조를 못하게 되므로 pthread_join 으로 받아온 m은 NULL 값이므로 segmentaiton fault 가 뜬다.
Locks
lock은 임계지점(critical section)에 mutual exclusion을 제공한다.
Interface
Usage
현재 thread에서 lock을 걸게 되면 다른 thread들은 실행 될 수 없다. 따라서 critical section에 들어가기 전에 사용하면 된다.
All locks must be properly initialized.
모든 lock들은 사용되기 전에 initialized 줘야하고, assert를 통해 잘 초기화 되었는지 꼭 확인해 줘야 한다.
trylock : return failure if the lock is already held
timelock : return after a timeout
Condition Variables
Condition variables are useful whe some kind of signaling must take place between threads.
pthread_cond_wait
- Put the calling thread to sleep
- Wait for some other thread to signal it
pthread_cond_signal
- Unblock at least one of the threads that are blocked on the condition variable
'3-2 > 운영체제' 카테고리의 다른 글
Lock-based Concurrent Data Structures (0) | 2021.11.13 |
---|---|
Locks (0) | 2021.11.12 |
Concurrency (0) | 2021.11.08 |
LRU Implementation in more detail (0) | 2021.11.08 |
Swapping Policies (0) | 2021.11.08 |