【问题标题】:Pass an int array in pthread function in C在 C 中的 pthread 函数中传递一个 int 数组
【发布时间】:2015-10-23 13:00:06
【问题描述】:

我正在编写一个用于锻炼的多线程程序。给定一个随机数数组(100 个位置),我必须将其除以 5 个数组并将它们分配给 5 个 pthread 以找到最大值并将这些值返回给找到它们之间最大值的主函数。到目前为止,这是我的代码:

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

#define NUM_THREADS 5
#define DIM_VETTORE 100


void *Calcola_max(void* args){


}



int main(){
    int vettore[DIM_VETTORE];
    int t;
    int i;
    srand(time(NULL));

/*riempio il vettore con numeri random*/
        for (i=0; i<DIM_VETTORE; i++){
        vettore[i]=rand() % 500 + 1;
        printf("Numero in posizione %d: %d\n", i,vettore[i]);
        }

/*indico le dimensioni di ogni array splittato*/
    int dimensione_split=DIM_VETTORE/NUM_THREADS;
    printf("Dimensione degli array splittati: %d\n", dimensione_split);

/*creo tutti i thread*/
        pthread_t thread[NUM_THREADS];
        for (t=0;t<NUM_THREADS; t++){
        printf("Main: creazione thread %d\n", t);
        int rc;

            rc=pthread_create(&thread[t], NULL, Calcola_max, &vettore);

                if (rc) {
                printf("ERRORE: %d\n", rc);
                exit(-1);
                }
        }
}

我的问题是:如何拆分数组?以及如何将每个数组传递给每个 pthread?提前致谢


所以,我已经编辑了我的代码,但这次它在创建 pthread 后给了我分段错误。 IMO我以这种方式传递线程函数的参数是错误的:

...   
pthread_create(&thread[t], NULL, Calcola_max, (void *)&start[i]);
...

void *Calcola_max(void *a){
...
s = *(int *)a;
...

这是我的完整代码:

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

#define NUM_THREADS 5
#define DIM_VETTORE 100
int vettore[DIM_VETTORE];
int    start[100];
int max[100];       //vettore dove vanno tutti i minimi calcolati dai pthread



void *Calcola_max(void *a){
    int array;
    int n=DIM_VETTORE/NUM_THREADS;
    int s, i;
    int start, stop;
    int massimo;

    s = *(int *)a;
    start = s * n;

    if ( s != (NUM_THREADS-1) )
   {
      stop = start + n;
   }
   else
   {
      stop = DIM_VETTORE;
   }
    massimo=vettore[start];

    for (i = start+1; i < stop; i++ )
   {


      if ( vettore[i] > massimo )
         massimo = vettore[i];
   }

   max[s] = massimo;



    //array = (int) a;

    int k;
    int max=0;  
        for (k=0; k<DIM_VETTORE; k++){      //qui devo mettere il range corrente del vettore, o mettere uno split di vettore
        printf("Massimo corrente: %d\n",max);
            if (vettore[k]>max) max=vettore[k];     
        }

//return(NULL);     /* Thread exits (dies) */   
pthread_exit;
}



int main(){
    //int vettore[DIM_VETTORE];
    int massimo;       //vettore dei minimi finale in cui opero confronto e calcolo il minimo
    int t;
    int i, j;
    srand(time(NULL));

/*riempio il vettore con numeri random*/
        for (i=0; i<DIM_VETTORE; i++){
        //int num;          //contenitore numero random
        vettore[i]=rand() % 500 + 1;
        //printf("Numero in posizione %d: %d\n", i,vettore[i]);
        }

/*indico le dimensioni di ogni array splittato*/
    int dimensione_split=DIM_VETTORE/NUM_THREADS;
    printf("Dimensione degli array splittati: %d\n", dimensione_split);

/*creo tutti i thread*/
        pthread_t thread[NUM_THREADS];
        for (t=0;t<NUM_THREADS; t++){
        start[i] = i;
        printf("Main: creazione thread %d\n", t);
        int rc;
        //int pos_vettore;
            //for (pos_vettore=0; pos_vettore<100; pos_vettore+20){
            rc=pthread_create(&thread[t], NULL, Calcola_max, (void *)&start[i]);

                if (rc) {
                printf("ERRORE: %d\n", rc);
                exit(-1);
                }
            //}
        }
        /*joino i threads*/
        for (i = 0; i < NUM_THREADS; i++)
      pthread_join(thread[i], NULL);

    massimo= max[0];
    sleep(3);
        for (i = 1; i < NUM_THREADS; i++)
                if ( max[i] > massimo )
            massimo = max[i];

    printf("Il massimo è: %d\n", massimo);


}

【问题讨论】:

  • 您不需要拆分数组。您将指向数组的指针以及要处理的间隔(0..24、25..49 等)传递给每个线程。
  • ^^ @MichaelWalz 所说的。 Typedef up 一个 'ArrayDescriptor' 结构,它有一个数组指针和一个长度。 malloc 为每个线程分配一个,将其初始化为指向主数组的一个子部分,然后将 ArrayDescriptor 地址作为 pthread_create 'void*' 参数传递。在线程函数中,将其转换回来,使用它。不要忘记在线程函数退出之前释放它。

标签: c arrays linux pthreads posix


【解决方案1】:

您的 pthread 可以轻松访问主程序中的数组。您不需要为此拆分数组。只需确保 pthread 正在修改主数组的不同部分。使用structtypedef 将相关信息传递给pthread 函数。

【讨论】:

【解决方案2】:

如前所述,您不会拆分或复制数组。

线程与创建它们的进程共享相同的内存区域,因此您可以只传递数组。

如果游戏的目的是从使用线程中获得一些性能增益,那么您几乎肯定不想使用堆分配内存。

不得不说可能有更好的方法,我可能会在线程之前查看 SIMD 或其他一些 SSE 扩展,但无论如何......

下面的example,经过了大约 5 分钟的思考,需要更好的错误检查和逻辑验证(因为它是周日上午 9 点),它展示了我认为最有效的线程计算方法可能是.

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

#define THREADS 5
#define DATA 100

typedef struct _pthread_arg_t {
    pthread_t thread;
    int *data;
    unsigned int end;
    int max;
} pthread_arg_t;

void* pthread_routine(void *arg) {
    pthread_arg_t *info = (pthread_arg_t*) arg;
    int *it = info->data,
        *end = info->data + info->end;

    while (it < end) {
        if (*it > info->max) {
            info->max = *it;
        }
        it++;
    }

    pthread_exit(NULL);
}

int main(int argc, char *argv[]) {
    pthread_arg_t threads[THREADS];
    int data[DATA],
        thread = 0,
        limit = 0,
        result = 0;

    memset(&threads, 0, sizeof(pthread_arg_t) * THREADS);   
    memset(&data, 0, sizeof(int) * DATA);

    while (limit < DATA) {
        /* you can replace this with randomm number */
        data[limit] = limit;
        limit++;
    }

    limit = DATA/THREADS;

    while (thread < THREADS) {
        threads[thread].data = &data[thread * limit];
        threads[thread].end = limit;
        if (pthread_create(&threads[thread].thread, NULL, pthread_routine, &threads[thread]) != 0) {
            /* do something */
            return 1;
        }
        thread++;
    }

    thread = 0;
    while (thread < THREADS) {
        if (pthread_join(threads[thread].thread, NULL) != 0) {
            /* do something */
            return 1;
        }
        thread++;
    }

    thread = 0;
    result = threads[0].max;
    printf("result:\n");
    while (thread < THREADS) {
        printf("\t%d - %d: %d\n",
            thread * limit,
            thread * limit + limit - 1,
            threads[thread].max);
        if (threads[thread].max > result) {
            result = threads[thread].max;
        }
        thread++;
    }
    printf("max\t%d\n", result);

    return 0;
}

请注意,这是无锁和 malloc 的,您可以通过更多的摆弄来进一步减少指令......

【讨论】:

    猜你喜欢
    • 2013-10-15
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2022-01-06
    相关资源
    最近更新 更多