我在 Windows 上使用 pthreads.h 来做一个简单的光线追踪器。似乎主要功能没有等待线程完成。当我像这样运行程序时(我现在简化了它,只测试线程,但它仍然给出错误):
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。