定义声明全局变量lock
pthread_mutex_t lock;
在main函数中初始化该互斥锁
int main(int argc, char* argv[]) {
pthread_mutex_init(&lock, NULL);
// ... 省略
insert
会修改临界区的内容,所以需要修改put
函数:
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);
}
结果:
? gcc -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
MIT6.828 Fall2018 笔记 - Homework 6: Threads and Locking
原文:https://www.cnblogs.com/zsmumu/p/12757620.html