我有一个函数,它接收一对管道文件描述符,从一个管道中读取数字,对它们进行排序,然后通过第二个管道写回父对象:

void *sort_chunk(int fds[][2]) {
    close(fds[DOWN][WRITE]);
    FILE* fddr = fdopen(fds[DOWN][READ], "r");
    char str[25];
    vector<long int> nums;

    // Read from parent and sort
    while (fgets(str, 20, fddr)) {
        string fstr = string(str);
        fstr.erase(fstr.length() - 1); // Remove trailing line return
        nums.push_back(stol(fstr));
    }
    fclose(fddr);

    bubblesort(nums);

    // Write back to parent
    close(fds[UP][READ]);
    FILE* fduw = fdopen(fds[UP][WRITE], "w");
    for (auto it = nums.begin(); it != nums.end(); it++) {
        fprintf(fduw, "%ld\n", *it);
    }
    fclose(fduw);
    exit(0);
}
我想在多个子线程中运行此函数:
int fds[2][2];
pipe(fds[DOWN]);
pipe(fds[UP]);
pthread_create(&threads[i], NULL, sort_chunk, fds);
当我尝试创建线程时,我得到:
mysort.cc:139:38: error: invalid conversion from ‘void* (*)(int (*)[2])’ to ‘void* (*)(void*)’ [-fpermissive]
  139 |    pthread_create(&threads[i], NULL, sort_chunk, fds);
      |                                      ^~~~~~~~~~
      |                                      |
      |                                      void* (*)(int (*)[2])

最佳答案

您需要修复线程函数以匹配pthread_create期望的原型(prototype):

void *sort_chunk(void *fds_) {
    int (*fds)[2] = fds_;   // works for C -- need an explicit cast for C++
基本的问题是pthread_create期望带有单个void *参数的特定类型的函数指针,因此您不能以其他任何方式安全地调用它。
这在C语言中效果很好,但是在C++中,您需要在函数中使用一个显式的static_cast,这很丑陋。但是对于C++,您可能仍然应该使用std::thread。

关于c++ - 尝试创建线程时从 ‘void* (*)(int (*)[2])’无效转换为void *(*)(void *),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64091651/

10-11 23:04
查看更多