[英]Thread mutual exclusion: mutex_lock implemented with mutex_trylock
[英]Am I using the mutex_trylock correctly?
賽車手應該有平等的獲勝機會。 當我運行程序時,結果似乎是正確的,兩個賽車手都贏了大約一半的時間,但是我認為我沒有正確使用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);
}
當第一個線程鎖定B0時,如果第二個線程計划鎖定B1,則它將導致死鎖。 如果第一個互斥鎖已鎖定而第二個互斥鎖未鎖定,則釋放第一個互斥鎖並再次循環。 如果嘗試使用Mutex_lock而不是trylock,則此循環會更小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.