我创建了2个主题,其中一个应该总结随机数并显示它们的平均值,其次必须将它们相乘并显示它们。在编译和运行它之后只做这样的事情:image,有人可以帮忙,怎么做? Thread1是汇总和显示随机数平均值的函数,Thread2是乘以随机数的函数
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sched.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/types.h>
#include<time.h>
struct msgbuf {
long type;
int data;
};
void *thread_1(void *id)
{
static int i=0;
struct msgbuf buffer;
static int sum=0;
static double arytm=0;
if(msgrcv(*(int*)id,&buffer,sizeof(buffer.data),1,0)<0)
perror("msgrcv");
else
{
sum=sum+buffer.data;
arytm=sum/(i+1);
printf("Thread 1 Srednia arytm %f\n",arytm);
i=i+1;
}
return NULL;
}
void *thread_2(void *id)
{
struct msgbuf buffer;
static unsigned long long iloczyn=1;
if(msgrcv(*(int*)id,&buffer,sizeof(buffer.data),1,0)<0)
perror("msgrcv");
else
{
iloczyn=iloczyn*buffer.data;
printf("Thread 2 Iloczyn %llu\n",iloczyn);
}
return NULL;
}
int main()
{
srand(time(NULL));
int j,random;
pthread_t thread_id[2];
int key = ftok("/tmp",8);
if(key<0)
perror("ftok");
int id = msgget(key,0600|IPC_CREAT|IPC_EXCL);
if(id==-1)
{
id=msgget(key,0600|IPC_CREAT);
if(id==-1)
perror("msgget");
}
struct msgbuf buffer;
for(j=0;j<20;j++)
{
printf("Iteracja nr %d\n",j+1);
random=128+ rand()%128;
printf("Random number %d\n",random);
buffer.type=1;
buffer.data= random;
if(msgsnd(id,&buffer,sizeof(buffer.data),0)<0)
perror("msgsnd");
int return_code = pthread_create(&(thread_id[0]),NULL,thread_1,(void *)&id);
if(return_code!=0)
fprintf(stderr,"pthread_create() error: %d\n",return_code);
int return_code1= pthread_create(&(thread_id[1]),NULL,thread_2,(void *)&id);
if(return_code1!=0)
fprintf(stderr,"pthread_create() error: %d\n",return_code1);
sleep(1);
}
if(msgctl(id,IPC_RMID,0)<0)
perror("msgctl");
return 0;
}