I am using pthreads.h on Windows, for a simple raytracer. It seems like the main function is not waiting for the threads to finish. When I just run the program like this(I now simplified it, to just test the threads, but it still gives the error):
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);
}
}
}
The image won't be completed and only renders a couple of pixels. When I add a sleep however, the image does finish. Leading me to believe that pthread_join doesn't wait, even though the documentation says so. What am I missing here?
Edit: Added error checking, it returns error code 3 for the pthread_join.