简体   繁体   English

使用pthread并行编程

[英]Parallel programming using pthread

I have just started learning parallel programming using pthreads . 我刚刚开始学习使用pthreads并行编程。 So, for the learning purpose I tried sum of two integer arrays parallely. 因此,出于学习目的,我尝试并行计算两个整数数组的总和。 I have declared struct construct with three array variables a , b and c . 我已经声明了带有三个数组变量abc struct construct I want to do addition of a , b and store the result in c . 我想加ab并将结果存储在c

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

#define MAX 6

struct data {
  int a[MAX];
  int b[MAX];
  int c[MAX];
};

void *addition(void *index) {
  struct data *d1 = (struct data *)index;
  printf("value of d1 structure=%d\n", d1->a[0]);
}

int main() {
  int i, j, t;
  struct data *item = NULL;
  pthread_t threads[MAX];

  item = (struct data *)malloc(sizeof *item);

  printf("enter the value for arrray a\n");
  for (i = 0; i < MAX; i++) {
    scanf("%d", &item->a[i]);
  }

  printf("enter the value of array b\n");
  for (j = 0; j < MAX; j++) {
    scanf("%d", &item->b[j]);
  }

  for (t = 0; t < MAX; t++) {
    pthread_create(&threads[t], NULL, addition, (void *)&item);
  }
}

Here, as of now I have not added the addition of arrays in the function addition() , because in pthread_create() when I am passing the three arguments with the help of structure , in function addition the variables a and b are not getting copied. 在这里,到目前为止,我还没有在函数pthread_create()添加数组的addition() ,因为在pthread_create()当我借助structure传递三个参数时,在函数添加中变量ab不会被复制。 Printing a is giving me garbage value. 打印a给我垃圾价值。 Can anybody help me how to copy the structure variable to the function argument called by pthread_create() . 任何人都可以帮助我如何将structure变量复制到pthread_create()调用的函数参数中。

pthread_create Function : pthread_create函数:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

Kindly note (*arg) is pointer to the arg . 请注意(*arg)是指向arg指针。 You have created struct data *item as a pointer then you are passing its address ie pointer to pointer. 您已经将struct data *item创建为指针,然后传递其地址,即指向指针的指针。

pthread_create(&threads[t], NULL, addition, (void *)&item);

Change the call to 更改为

pthread_create(&threads[t], NULL, addition, (void *)item).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM