Previous chapter
Main QUEST
ํน์ ์๋ฃ๊ตฌ์กฐ๊ฐ ์ฃผ์ด์ก์ ๋, ์ด๋ค ๋ฐฉ์์ผ๋ก ๋ฝ์ ์ถ๊ฐํด์ผ ๊ทธ ์๋ฃ ๊ตฌ์กฐ๊ฐ ์ ํํ๊ฒ ๋์ํ๊ฒ ๋ง๋ค ์ ์์๊น?
๋ค์์ ์ค๋ ์ค๊ฐ ํด๋น ์๋ฃ๊ตฌ์กฐ๋ฅผ ๋์์ ์ ๊ทผํ๋๋ก ํด์ ์ฑ๋ฅ์ ์ด๋ป๊ฒ ํฅ์์ํฌ ์ ์์๊น?
์ฌ๋ฌ ์ค๋ ๋๊ฐ ์ ๊ทผํด๋ ๊ฒฝ์์กฐ๊ฑด ์์ด ์์ ํ๊ฒ ์๋ํ๋ ๊ฒ์ thread safe์ํ๋ผ๊ณ ํ๋ค.
๋ํ ์ผ๋ง๋ ๋์์ ์ ๊ทผ๊ฐ๋ฅํ๋๋ก ํ ์ง๋ ๊ณ ๋ คํ๋ ๊ฒ์ด ์ข์ ๊ฒ์ด๋ค.
Concurrent Counter
typedef struct __counter_t {
int value;
pthread_mutex_t lock;
} counter_t;
void init(counter_t *c) {
c->value = 0;
pthread_mutex_init(&c->lock, NULL);
}
C
๋ณต์ฌ
์ผ๋ฐ์ ์ผ๋ก์นด์ดํฐ์ฉ ๋ณ์ + ๋ฝ์ ํ๋์ ๊ตฌ์กฐ์ฒด๋ก ์ ์ธํ์ฌ ๋ค๋ฃฌ๋ค.
void increment(counter_t *c) {
pthread_mutex_lock(&c->lock);
c->value++;
pthread_mutex_unlock(&c->lock);
}
void decrement(counter_t *c) {
pthread_mutex_lock(&c->lock);
c->value--;
pthread_mutex_unlock(&c->lock);
}
int get(counter_t *c) {
pthread_mutex_lock(&c->lock);
int rc = c->value;
pthread_mutex_unlock(&c->lock);
return rc;
}
C
๋ณต์ฌ
ใ
์ ํจ์๋ฅผ ํตํด์๋ง ๊ฐ์ ธ์ฌ ์ ์๋๋ก ํ๋ค! (์ผ์ข
์ getter์ setter๊ฐ์ ๋๋์ธ)
Simple, But no Extension
Scalable Counting
โ ๊ผญ ์ ๋ฆฌํ์์คโฆ
Concurrent Linked List
typedef struct __node_t {
int key;
struct __node_t *next;
} node_t;
typedef struct __list_t {
node_t *head;
pthread_mutex_t lock;
} list_t;
void List_Init(list_t *L) {
L->head = NULL;
pthread_mutex_init(&L->lock, NULL);
}
C
๋ณต์ฌ
int List_Insert(list_t *L, int key) {
pthread_mutex_lock(&L->lock);
node_t *new = malloc(sizeof(node_t));
if (new == NULL) {
perror("malloc");
pthread_mutex_unlock(&L->lock);
return -1; // fail
}
new->key = key;
new->next = L->head;
L->head = new;
pthread_mutex_unlock(&L->lock);
return 0; // success
}
C
๋ณต์ฌ
int List_Lookup(list_t *L, int key) {
pthread_mutex_lock(&L->lock);
node_t *curr = L->head;
while (curr) {
if (curr->key == key) {
pthread_mutex_unlock(&L->lock);
return 0; // success
}
curr = curr->next;
}
pthread_mutex_unlock(&L->lock);
return -1; // failure
}
C
๋ณต์ฌ
Concurrent Queue
Concurrent Hash Table
Conclusion
Next chapter