尝试在 Unix 环境中得到类似这样的输出:
线程 0 - 0、线程 1 - 0、线程 2 - 0、线程 2 - 1、线程 2 - 2、 线程 3 - 0, ...
我确信 main() 没问题,但是这是我第一次使用函数指针。我可能会犯一些明显的错误。总之...帮助。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
struct thread_data {
int id;
};
typedef int (*Start) (void runner(void *), struct thread_data *params, pthread_t *thread);
typedef int (*Join) (int id);
typedef struct _Thread {
pthread_t id;
Start start;
Join join;
} Thread;
void runner();
int *start(void runner(void *), pthread_t* params, Thread *thread);
int *join(int id);
int main(int argc, char *argv[]) {
srand(time(0));
int i, num = 4;
struct thread_data params[num];
for (i=0; i<num; i++) params[i].id = i;
Thread thread[num];
for (i=0; i<num; i++) {
thread[i].start = start;
thread[i].join = join;
}
for (i=0; i<num; i++) {
thread[i].start(runner, ¶ms[i], &thread[i].id);
}
for (i=0; i<num; i++) {
thread[i].join(thread[i].id);
}
pthread_exit(NULL);
return 0;
}
void runner(){
struct thread_data *data;
int i;
for (i = 0; i < 10; i++){
printf("Thread %d - %d\n", data->id, i);
sleep((int) (rand()%2));
}
}
int *start(void runner(void *), pthread_t* params, Thread *thread){
pthread_create(&thread->id, NULL, runner(void *), ¶ms);
}
int *join (int id){
pthread_join(id, NULL); //thread->id, NULL)
}
但我收到这些错误
temp03.c: In function ‘main’:
temp03.c:30: warning: assignment from incompatible pointer type
temp03.c:31: warning: assignment from incompatible pointer type
temp03.c: In function ‘start’:
temp03.c:51: error: expected expression before ‘void’
temp03.c:51: error: invalid use of void expression
30 和 31 是线程 [i]... 个,51 是最后一个
Thread thread[num];
for (i=0; i<num; i++) {
thread[i].start = start;
thread[i].join = join;
}
int *start(void runner(void *), pthread_t* params, Thread *thread){
pthread_create(&thread->id, NULL, runner(void *), ¶ms);
}
最佳答案
您的函数指针应返回
int
,而函数则返回int *
。实际上存在类型不匹配,您要么
更改函数类型定义以返回
int *
typedef int *(*Start) (void runner(void *), struct thread_data *params, pthread_t *thread); typedef int *(*Join) (int id);
或者修复函数以返回
int
int start(void runner(void *), pthread_t* params, Thread *thread); int join(int id);
这取决于您真正需要什么。
您的
runner
参数显然是另一个函数指针,但它没有这样声明,您必须通过编写类似的内容来修复它typedef int *(*Start) (void (*runner)(void *), ... )
相反。
当然也要修复定义。
关于c - C 中的多线程程序 - 从不兼容的指针类型进行赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49035800/