gpt4 book ai didi

c - 使用 pthread_create 时出现问题

转载 作者:行者123 更新时间:2023-11-30 18:37:49 25 4
gpt4 key购买 nike

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

#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;
}

我收到此错误:

warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type pthread_create(&thread[i], NULL, *squarer, &data[i]); ^

有人知道怎么解决吗?

谢谢

最佳答案

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

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

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

关于c - 使用 pthread_create 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35781701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com