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