- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我的大学有一个关于 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/
我想在本地移动并启动我的 wordpress 站点。 我无法识别 wp-bakery 文件夹,实际上我不知道插件文件夹中或主题中的插件文件夹(我有 truemag 主题) 此致, 达留什 最佳答案 W
我最近在学习中遇到了面包店算法,只需要澄清一些事情。 如果进程没有选择大于所有现有票证的票号,面包店算法是否可能违反互斥? 在没有争用的情况下,在临界区之后将 number[i] 设置为零是否对成功很
我正在尝试覆盖 WP Bakery 的选项卡动画,该动画可将内容垂直滑入和滑出 View 。我是一名 JS 经验有限的前端设计师。该站点运行一个主题,但根据我在代码中可以看出的内容,选项卡和动画被编码
我正在尝试覆盖 WP Bakery 的选项卡动画,该动画可将内容垂直滑入和滑出 View 。我是一名 JS 经验有限的前端设计师。该站点运行一个主题,但根据我在代码中可以看出的内容,选项卡和动画被编码
我的 Python 项目中有一个奇怪的问题。它使用 SQLAlchemy 和 Bakery 来准备查询。我有一个函数,它接受连接 (db)、面包店和对象数组。 此函数在 for 循环中被其他函数调用多
我是多线程编程的新手,我尝试编写 Bakery Lock Algorithm在 C 中。 代码如下: int number[N]; // N is the number of threads
我正在尝试学习vaadin JAVA框架。我正在查看 Bakery App 的代码。在 LoginView.java 中,调用 setAction('login') 来处理成功的身份验证。我想知道这是
我有一行使用 WP Bakery(以前的 Visual Composer),其中有两列只是背景图像。没有内容。但是,当我在 WordPress 的前端编辑器中将行设置为全高时,该行仍然不会垂直拉伸(s
如资源所述,Bakery 算法应该是无死锁的。但是当我试图理解伪代码时,我想到了一条可能引发死锁的行(据我所知)。 引用下面的代码,在 Lock() 函数中,我们有一行内容是 label[i] = m
我正在尝试通过记录的函数 vc_add_param() 以这种方式将 ID 属性添加到 Visual Composer 中的行: $attributes = array( 'type' => 'te
我的大学有一个关于 n 个进程的临界区问题的项目。我在 c 中为 2 个进程编写了代码,但我无法弄清楚如何让它为 n 个进程工作。代码在 C 语言中用于 linux 线程。 这是 2 个进程的代码。
所以,我不熟悉 C 中的共享内存和 shm 函数。 我有两个程序;主人和奴隶。在最一般的意义上:主程序在共享内存中创建一个 sharedNum 整数,并 fork 出多个执行从程序的进程。然后,从属程
我们正在为客户网站使用 WP Bakery Page Builder。该插件工作正常,但有时角色管理器中的设置会重置 Composer 应该使用的帖子类型。 我们正在研究以编程方式破解设置以将其设置为
我们正在为客户网站使用 WP Bakery Page Builder。该插件工作正常,但有时角色管理器中的设置会重置 Composer 应该使用的帖子类型。 我们正在研究以编程方式破解设置以将其设置为
我是一名优秀的程序员,十分优秀!