gpt4 book ai didi

c - 如何在 c 中为 n 个进程编写临界区代码(Bakery 算法)

转载 作者:太空宇宙 更新时间:2023-11-04 12:30:35 25 4
gpt4 key购买 nike

我的大学有一个关于 n 个进程的临界区问题的项目。我在 c 中为 2 个进程编写了代码,但我无法弄清楚如何让它为 n 个进程工作。代码在 C 语言中用于 linux 线程。

这是 2 个进程的代码。

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

int flag[2];
int turn;
const int MAX = 1e9;
int ans = 0;


void lock_init(){
flag[0]=flag[1]=0;
turn = 0;
}

void lock(int self){
flag[self]=1;
turn = 1-self;

while(flag[1-self]==1 && turn == 1-self);
}

void unlock(int self){
flag[self]=0;
}

void* func(void *s){
int i=0;
int *limitptr = (int*) s;
int self = *limitptr;
printf("Thread %d in queue for critical section\n",self);

lock(self);

printf("Thread %d in critical section\n",self);
for(i=0;i<MAX;i++){

ans++;

}
printf("Thread %d done counting\n",self);
printf("Thread %d is exiting critical section\n",self);
unlock(self);
}

int main(){

pthread_t p1, p2;
int a=0,b=1;
lock_init();

pthread_create(&p1, NULL, func, &a);
pthread_create(&p2, NULL, func, &b);

pthread_join(p1, NULL);
pthread_join(p2, NULL);

printf("Exiting Main\n");
return 0;
}

如有任何帮助,我们将不胜感激。谢谢。 :)

最佳答案

使用互斥体

#include <pthread.h>

像这样声明互斥体:

pthread_mutex_t myMutex = PTHREAD_MUTEX_INITIALIZER;

然后在关键部分调用的开始:

pthread_mutex_lock( &myMutex );

并且在关键部分调用结束时:

pthread_mutex_unlock( &myMutex );

不管有多少线程正在使用那个临界区,一次只有一个线程能够访问它

关于c - 如何在 c 中为 n 个进程编写临界区代码(Bakery 算法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43422744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com