c - C 中的多线程程序 - 从不兼容的指针类型进行赋值

标签 c multithreading

尝试在 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, &params[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 *), &params);
}

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 *), &params);
}

最佳答案

  1. 您的函数指针应返回 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);
      

    这取决于您真正需要什么。

  2. 您的 runner 参数显然是另一个函数指针,但它没有这样声明,您必须通过编写类似的内容来修复它

    typedef int *(*Start) (void (*runner)(void *), ... )
    

    相反。

    当然也要修复定义。

关于c - C 中的多线程程序 - 从不兼容的指针类型进行赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49035800/

相关文章:

c - 排序链表位置

c - 处理嵌套结构访问

java - 无锁和无等待线程安全延迟初始化

java - Wicket 和多线程业务对象

c# - WinForm 应用程序 UI 在长时间运行期间挂起

在输入两个点的情况下应该打印否?

c - struct 中的字符串文字 - C

c - 正则表达式 <(.*?)> 返回 < 或 >

c - 以循环方法调度 pthread

python - 等待线程完成使用连接。很基本