簡體   English   中英

如何使用pthreads在c中返回數組?

[英]How to return an array in c using pthreads?

我試圖編寫一個程序,該程序通過將隨機向量傳遞給線程來使線程返回數字數組,並且線程返回向量的2倍。 程序運行良好,沒有得到預期的輸出。 代碼如下:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
void *myThreaddouble();

int i,sum[10],first[10]={10,20,30,40,50};

void *myThreaddouble()
{

int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}    

   pthread_exit(sum[i]);
}

int main()
{

 double total = omp_get_wtime();

 printf("This is using PThread\n");

  pthread_t tid1;
  pthread_create(&tid1, NULL, myThreaddouble, NULL);
  printf("Double of the vector:-   \n");
  for ( i = 0 ; i < 5 ; i++ )
  {
    printf(" %d\n",(int) sum[i]);
  }
  pthread_join(tid1, sum[i]);

  total = omp_get_wtime() - total;
  printf("%lf is time to add\n",total);
  printf("\n");

  return 0;

}

輸出如下:

This is using PThread
Double of the vector:-   
 0
 0
 0
 0
 0
0.000188 is time to add

這不是預期的輸出,因此有人可以告訴我此代碼中的錯誤是什么以及如何使用pthread返回數組。 在i中,我應該能夠對所有返回值求和。

我使用gcc qc -lpthread -lrt -fopenmp命令來編譯該程序。

先感謝您!

可能是由於int *sum[10];這一行引起的int *sum[10]; 在此功能中:

void *myThreaddouble()
{

int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}

您正在創建一個局部變量sum ,它比全局變量sum優先,因為它在內部范圍內。 嘗試將其刪除。

妳去 我已自由注釋掉時間計算部分。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
void *myThreaddouble();

int i,sum[10],first[10]={10,20,30,40,50};

void *myThreaddouble(void *a)
{

//int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}    

   //pthread_exit(sum[i]);
   pthread_exit(NULL);
}

int main()
{

// double total = omp_get_wtime();

 printf("This is using PThread\n");

  pthread_t tid1;
  pthread_create(&tid1, NULL, myThreaddouble, NULL);
  printf("Double of the vector:-   \n");

  //pthread_join(tid1, sum[i]);
  pthread_join(tid1, NULL);

  for ( i = 0 ; i < 5 ; i++ )
  {
    printf(" %d\n",(int) sum[i]);
  }
 // pthread_join(tid1, sum[i]);

  //total = omp_get_wtime() - total;
  //printf("%lf is time to add\n",total);
  printf("\n");

  return 0;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM