尝试在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&amp; 31是线程[i] ...... 1,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);
}
答案 0 :(得分:0)
当函数返回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 *), ... )
代替。
当然也要修改定义。