使用pthread_create时出现问题

时间:2016-03-03 19:51:37

标签: c pthreads

当我尝试编译以下代码时:

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

#define ARRAYSIZE 17
#define NUMTHREADS 4

struct ThreadData {
    int start, stop;
    int* array;
};

/* puts i^2 into array positions i=start to stop-1 */
void* squarer(struct ThreadData* td) {
    struct ThreadData* data=(struct ThreadData*) td;
    int start=data->start;
    int stop=data->stop;
    int* array=data->array;
    int i;

    for (i=start; i<stop; i++) {
        array[i]=i*i;
    }

    return NULL;
}

int main(void) {
    int array[ARRAYSIZE];
    pthread_t thread[NUMTHREADS];
    struct ThreadData data[NUMTHREADS];
    int i;
    /*
        this has the effect of rounding up the number of tasks
        per thread, which is useful in case ARRAYSIZE does not
        divide evenly by NUMTHREADS.
    */
    int tasksPerThread=(ARRAYSIZE+NUMTHREADS-1)/NUMTHREADS;

    /* Divide work for threads, prepare parameters */
    for (i=0; i<NUMTHREADS; i++) {
        data[i].start=i*tasksPerThread;
        data[i].stop=(i+1)*tasksPerThread;
        data[i].array=array;
    }
    /* the last thread must not go past the end of the array */
    data[NUMTHREADS-1].stop=ARRAYSIZE;

    /* Launch Threads */
    for (i=0; i<NUMTHREADS; i++) {
        pthread_create(&thread[i], NULL, squarer , &data[i]);
    }

    /* Wait for Threads to Finish */
    for (i=0; i<NUMTHREADS; i++) {
        pthread_join(thread[i], NULL);
    }

    /* Display Result */
    for (i=0; i<ARRAYSIZE; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    return 0;
}

我收到此错误:

  

警告:从不兼容的指针类型pthread_create(&amp; thread [i],NULL,* squarer,&amp; data [i])传递'pthread_create'的参数3;                                          ^

有谁知道如何修复它?

由于

2 个答案:

答案 0 :(得分:2)

函数squarer的类型为void *(*)(struct ThreadData *),但pthread_create需要void *(*)(void *)类型的参数。这些类型是不兼容的。

更改您的函数以获取void *参数,然后将其分配给struct ThreadData *

void* squarer(void *td) {
    struct ThreadData* data=td;
    ....

答案 1 :(得分:1)

传递给pthread_create()的第三个参数必须是void * (*)(void *)类型。

您的类型为void * (*)(struct ThreadData * td)

修复此更改

void* squarer(struct ThreadData* td) {
  struct ThreadData* data=(struct ThreadData*) td;

成为

void* squarer(void * td) {
  struct ThreadData * data = td;
相关问题