我在Windows上使用pthreads.h以获得简单的raytracer。似乎主要功能不是在等待线程完成。当我像这样运行程序时(我现在将其简化为仅测试线程,但仍会给出错误):

typedef struct {
    unsigned int id;
} Thread_Data;

void* render_band(void* arg) {
    Thread_Data* data = (Thread_Data*)arg;
    printf("This is thread number %d", data->id);
    pthread_exit(0);
}

int main() {
    pthread_t threads[NUM_THREADS];
    Thread_Data data[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) {
        data[i].id = id;

        int rc = pthread_create(&threads[i], NULL, render_band, &data[i]);
        if (rc) {
            printf("[ERROR] From pthread_create: %d\n", rc);
        }
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        int rc = pthread_join(threads[i], NULL);
        if (rc) {
            printf("[ERROR] From pthread_join: %d\n", rc);
        }
    }
}


该图像将不会完成,只能渲染几个像素。
但是,当我添加睡眠时,图像确实完成了。使我相信pthread_join不会等待,即使文档中是这样说的。我在这里想念什么?

编辑:添加了错误检查,它为pthread_join返回错误代码3。

最佳答案

很抱歉浪费大家的时间。问题最终是图书馆本身。当我在Windows上寻找pthreads.h时,我在sourceforge上找到了一些库。但是显然MinGW已经有了pthread支持,并且搞砸了所有东西。因此,对于存在相同问题的人们,只需使用MinGW随附的解决方案。

关于c - pthread_join不等待线程完成,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50891949/

10-12 16:18
查看更多