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