Homework: Threads and Lockinghtml
定義聲明全局變量lock
函數
pthread_mutex_t lock;
在main函數中初始化該互斥鎖code
int main(int argc, char* argv[]) { pthread_mutex_init(&lock, NULL); // ... 省略
insert
會修改臨界區的內容,因此須要修改put
函數:htm
static void put(int key, int value) { int i = key % NBUCKET; pthread_mutex_lock(&lock); insert(key, value, &table[i], table[i]); pthread_mutex_unlock(&lock); }
結果:pdo
❯ clang -g -O2 ph.c -pthread ❯ ./a.out 2 1: put time = 0.021635 0: put time = 0.021972 1: get time = 8.328023 1: 0 keys missing 0: get time = 8.329496 0: 0 keys missing completion time = 8.351818