【问题标题】:Am I using the mutex_trylock correctly?我是否正确使用了 mutex_trylock?
【发布时间】:2018-10-29 23:17:06
【问题描述】:

参赛者应该有平等的获胜机会。当我运行程序时,结果似乎是正确的,两个赛车手都赢了大约一半的时间,但我认为我没有正确使用 mutex_trylock。它实际上是按照我的实现方式做的吗?我是 C 新手,所以对此我不太了解。

节目说明: 我们假设有两个赛车手,在一个矩形区域的两个对角线上。他们必须沿着该地区外围的道路穿行。长方形的相对两侧有两座桥。为了完成围绕此的一轮穿越,赛车手必须同时通过两座桥。比赛条件是

1) 一次只有一名赛车手可以通过。

2) 在一个回合开始之前,他必须请求并获得两个传球,然后在完成该回合后必须释放传球,并重新尝试获得下一轮的传球。

3) Racer1 (R1) 将首先获得桥接 B1,然后是 B0。 R0 将获得 B0,然后是 B1。

4) 前缀有最大轮数。谁先达到这个数字,谁就是赢家,比赛将停止。

这是开始之前的情况。

                 B0
        R0-------- ~  -------------
        |                          |
        |                          |
        |                          |
        |                          |
        --------- ~  ------------- R1
                  B1


#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>

#define THREAD_NUM 2  
#define MAX_ROUNDS 200000
#define TRUE  1 
#define FALSE 0

/* mutex locks for each bridge */
pthread_mutex_t B0, B1;

/* racer ID */
int r[THREAD_NUM]={0,1};

/* number of rounds completed by each racer */
int numRounds[THREAD_NUM]={0,0};

void *racer(void *); /* prototype of racer routine */

int main()
{
    pthread_t tid[THREAD_NUM];
    void *status;
    int i,j;

    /* create 2 threads representing 2 racers */
    for (i = 0; i < THREAD_NUM; i++)
   {
       /*Your code here */
       pthread_create(&tid[i], NULL, racer, &r[i]);

    }

    /* wait for the join of 2 threads */
     for (i = 0; i < THREAD_NUM; i++)
    {
         /*Your code here */
         pthread_join(tid[i], &status);
    }

    printf("\n");
    for(i=0; i<THREAD_NUM; i++)
        printf("Racer %d finished %d rounds!!\n", i, numRounds[i]);

 if(numRounds[0]>=numRounds[1]) printf("\n RACER-0 WINS.\n\n");
 else  printf("\n RACER-1 WINS..\n\n");

return (0);
}


void *racer(void  *arg)
{
  int  index = *(int*)arg, NotYet;

    while( (numRounds[0] < MAX_ROUNDS) && (numRounds[1] < MAX_ROUNDS) )
 {

   NotYet = TRUE;

    /* RACER 0 tries to get both locks before she makes a round */
   if(index==0){
     /*Your code here */
     pthread_mutex_trylock(&B0);
     pthread_mutex_trylock(&B1);



   }

    /* RACER 1 tries to get both locks before she makes a round */
   if(index==1){
      /*Your code here */
     pthread_mutex_trylock(&B1);
     pthread_mutex_trylock(&B0);
     }
    numRounds[index]++;      /* Make one more round */


    /* unlock both locks */
    pthread_mutex_unlock(&B0);
    pthread_mutex_unlock(&B1);

       /* random yield to another thread */

     }

printf("racer %d made %d rounds !\n", index, numRounds[index]);

pthread_exit(0);

}

【问题讨论】:

  • 由于您没有检查函数的返回值以查看它是否成功...不,您没有正确使用它。

标签: c synchronization mutex


【解决方案1】:

当第一个线程锁定 B0,如果第二个线程被调度锁定 B1,则会导致死锁。如果第一个互斥锁被锁定而第二个未锁定,则释放第一个互斥锁并再次循环。如果尝试使用 mutex_lock 而不是 trylock,此循环可以更小。

【讨论】:

    猜你喜欢
    • 2011-07-14
    • 2014-07-19
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多