闲的蛋疼做了一个6.828的homework
就是这里 https://pdos.csail.mit.edu/6.828/2018/homework/barrier.html
就是说需要我们利用给的一个mutex,一个条件变量,实现一个barrier.
感觉barrier就是书上讲的那种sleep lock。具体到这个例子,前面说的mutex和条件变量,也就是下面的mutex和cond,分别就是一个spinlock和一个sleeplock。
pthread_cond_wait(&cond, &mutex); // go to sleep on cond, releasing lock mutex pthread_cond_broadcast(&cond); // wake up every thread sleeping on cond
实际填充的内容在barrier{}里面,实际上就是控制bstate.nthread的值,每一个线程都检测一下这个值,来知道自己是第一个还是第二个进入线程的,如果是第一个的话就挂起来,是第二个的话就把第一个唤醒,这样来保证两个线程一起进入每个round。
我刚开始做的时候忘记每轮之后要round++了,困惑了好久。。。
#include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <assert.h> #include <pthread.h> // #define SOL static int nthread = 1; static int round = 0; struct barrier { pthread_mutex_t barrier_mutex; pthread_cond_t barrier_cond; int nthread; // Number of threads that have reached this round of the barrier int round; // Barrier round } bstate; static void barrier_init(void) { assert(pthread_mutex_init(&bstate.barrier_mutex, NULL) == 0); assert(pthread_cond_init(&bstate.barrier_cond, NULL) == 0); bstate.nthread = 0; } static void barrier() { pthread_mutex_lock(&bstate.barrier_mutex); if (!(bstate.nthread)) { bstate.nthread++; pthread_cond_wait(&(bstate.barrier_cond), &(bstate.barrier_mutex)); } else { bstate.nthread--; bstate.round++; pthread_cond_broadcast(&(bstate.barrier_cond)); } pthread_mutex_unlock(&bstate.barrier_mutex); } static void * thread(void *xa) { long n = (long) xa; long delay; int i; for (i = 0; i < 20000; i++) { int t = bstate.round; assert (i == t); barrier(); usleep(random() % 100); } } int main(int argc, char *argv[]) { pthread_t *tha; void *value; long i; double t1, t0; if (argc < 2) { fprintf(stderr, "%s: %s nthread\n", argv[0], argv[0]); exit(-1); } nthread = atoi(argv[1]); tha = malloc(sizeof(pthread_t) * nthread); srandom(0); barrier_init(); for(i = 0; i < nthread; i++) { assert(pthread_create(&tha[i], NULL, thread, (void *) i) == 0); } for(i = 0; i < nthread; i++) { assert(pthread_join(tha[i], &value) == 0); } printf("OK; passed\n"); }