zhuzilin's Blog

about

6.828 Homework Threads and Locking

date: 2019-03-01
tags: OS  6.828  

这次的作业应该是这几次中最简单的一次了。主要就是进行了一个有外链的哈希表的多线程插入和取值。

取值部分不会进行修改,所以不用加锁。只是在插入的部分注意到:

static void 
insert(int key, int value, struct entry **p, struct entry *n)
{
  struct entry *e = malloc(sizeof(struct entry));
  e->key = key;
  e->value = value;
  e->next = n;
  *p = e;
}

注意到这里的p是每个哈希值对应的链表的结尾,所以需要加锁,不然两个线程同时往一个相同的结尾插入,就会丢东西了。所以在main中初始化:

int
main(int argc, char *argv[])
{
...
  for (i = 0; i < NBUCKET; i++) {
    pthread_mutex_init(&lock[i], NULL);
  }
...
}

然后在put函数中insert的两侧加锁:

static 
void put(int key, int value)
{
  int i = key % NBUCKET;
  pthread_mutex_lock(&lock[i]);
  insert(key, value, &table[i], table[i]);
  pthread_mutex_unlock(&lock[i]);
}

就大功告成了。

测试一下:

$ ./ph 1
0: put time = 0.006135
0: get time = 7.487561
0: 0 keys missing
completion time = 7.493947
$ ./ph 2
1: put time = 0.010365
0: put time = 0.010435
1: get time = 7.301592
1: 0 keys missing
0: get time = 7.313720
0: 0 keys missing
completion time = 7.324801