使用pthread进行并行编程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用pthread进行并行编程相关的知识,希望对你有一定的参考价值。

我刚开始使用pthreads学习并行编程。因此,出于学习目的,我平行地尝试了两个整数数组的总和。我已经宣布struct construct有三个数组变量abc。我想添加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
", 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
");
  for (i = 0; i < MAX; i++) {
    scanf("%d", &item->a[i]);
  }

  printf("enter the value of array b
");
  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);
  }
}

在这里,截至目前我还没有在函数addition()中添加数组,因为在pthread_create()中,当我在structure的帮助下传递三个参数时,在函数中,变量ab没有被复制。打印a给我垃圾价值。任何人都可以帮我如何将structure变量复制到pthread_create()调用的函数参数。

答案

pthread_create功能:

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

请注意(*arg)是指向arg的指针。您已创建struct data *item作为指针,然后您传递其地址,即指针指针。

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

将通话更改为

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

以上是关于使用pthread进行并行编程的主要内容,如果未能解决你的问题,请参考以下文章

使用openmp进行合并排序

自旋锁和互斥锁区别

使用 pthread 进行锻炼,但我的代码中有一些意外行为

pthread库实现简单并行程序:Hello

Linux系统编程-(pthread)线程通信(读写锁)

如何在 Python 中进行并行编程?