C 生产者消费者问题
我正在尝试使用线程来翻译下面的场景。 procA { while (TRUE) { update(x); retrieve(y); } } procB { while (TRUE) { retrieve(x); update(y); } } 普罗卡{ while(TRUE){ 更新(x); 检索(y); } } procB{ while(TRUE){ 检索(x); 更新(y); } } 我已经为此编写了以下代码:C 生产者消费者问题,c,multithreading,producer-consumer,C,Multithreading,Producer Consumer,我正在尝试使用线程来翻译下面的场景。 procA { while (TRUE) { update(x); retrieve(y); } } procB { while (TRUE) { retrieve(x); update(y); } } 普罗卡{ while(TRUE){ 更新(x); 检索(y); } } procB{ whi
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define WORK_SIZE 10
pthread_mutex_t work_mutex;
int wa1[WORK_SIZE];
int wa2[WORK_SIZE];
void *funA(void *);
void *funB(void *);
int main(){
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,funA,(void *)wa1))
perror("pthread_create");
if(pthread_create(&tid2,NULL,funB,(void *)wa2))
perror("pthread_create");
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
void *funA(void *ptr){
int *x=ptr;
int i=0,j,num;
//sleep(1);
while(i<=10){
num=rand();
*x=num;
x+1;
j=*wa2;
printf("A: %d\n",j);
wa2+1;
i++;
}
return NULL;
}
void * funB(void *ptr){
int *y=ptr;
int a=0,b,num;
while(a<=10){
num=rand();
b=*wa1;
printf("B: %d\n",b);
wa1+1;
*y=num;
y+1;
a++;
}
return NULL;
}
#包括
#包括
#包括
#包括
#定义工作单位大小10
pthread_mutex_t work_mutex;
int wa1[工作尺寸];
int wa2[工作尺寸];
void*funA(void*);
void*funB(void*);
int main(){
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,funA,(void*)wa1))
perror(“pthread_create”);
if(pthread_create(&tid2,NULL,funB,(void*)wa2))
perror(“pthread_create”);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
返回0;
}
void*funA(void*ptr){
int*x=ptr;
int i=0,j,num;
//睡眠(1);
虽然(我十次迭代太少了,在上下文切换发生之前就已经处理好了,所以你看不到任何并发。很抱歉,我无法从你的代码中分辨出任何东西,因为它缺少缩进、注释和良好的变量名。使while循环无限,并告诉我们输出是什么样子。随机数仅为y被另一个进程更改,所以只有当它处于活动状态时才更改。还要记住,您的行“wa1+1”和“wa2+1”没有任何作用;它们必须是“wa1++”才能有效。哦,wa1和wa2从来没有写入过。这也是这些值不更改的原因。编辑:哦,是的,抱歉。这段代码太复杂了。当我将其命名为“wa1++”时它没有被编译,所以我把它改成了这种方式。这些基本上是递增指向的地址,我的印象是&wa1/&wa2每次循环迭代都会被更新。你能在这里指出我的错误吗。你所做的就像写3+1;
。在指针中递增地址要编写wa1=wa1+1
或wa1++
很抱歉,也需要执行这些活动。我的坏消息
A: 1258442020
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
B: 1317969989
A: 803738656
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
B: 1851766329
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464