MIT Operating Systems Lab: Multithreading

Barrier

requirement

implement a barrier: a point in an application at which all participating threads must wait until all other participating threads reach that point too. You’ll use pthread condition variables, which are a sequence coordination technique similar to xv6’s sleep and wakeup.

code

static void 
barrier()
{
  // YOUR CODE HERE
  //
  // Block until all threads have called barrier() and
  // then increment bstate.round.
  //
  pthread_mutex_lock(&bstate.barrier_mutex);
  // second condition_wait to ensure one thread waits here when re-enter barrier()races.
  while(round == 1)
    pthread_cond_wait(&bstate.barrier_cond, &bstate.barrier_mutex);
  bstate.nthread++;
  if(bstate.nthread == 1){
    round = 0;// the first thread entering the barrier.
  } 
  if(bstate.nthread != nthread){ // other threads except the last
    while(round != 1){
      pthread_cond_wait(&bstate.barrier_cond, &bstate.barrier_mutex);
    } // first condition wait to ensure other threads wait until the last completed
    if(--bstate.nthread == 1){
      pthread_cond_broadcast(&bstate.barrier_cond); 
      round = 0; // means other threads have been waked up.
      bstate.nthread = 0;
    }
  } else if(bstate.nthread == nthread){ // the last thread
    bstate.round++;
    round = 1; // flag means the last thread arrived.
    pthread_cond_broadcast(&bstate.barrier_cond); 
  }
  pthread_mutex_unlock(&bstate.barrier_mutex);
  
}

hints

the most important hint is the second one:

You have to handle the case in which one thread races around the loop before the others have exited the barrier. In particular, you are re-using the bstate.nthread variable from one round to the next. Make sure that a thread that leaves the barrier and races around the loop doesn’t increase bstate.nthread while a previous round is still using it.

summary

condition wait and signal is like sleep & wakeup in xv6. process wait for another process’s some event to happen. so all threads are splited into two parts: other threads and the last thread, other threads wait for the last thread’s event, the last thread emit the signal when arriving the end of barrier().

The code is based on lab updated Wednesday, 09-Dec-2020 18:30:26 EST

Please find complete code here github

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值