c - Thread not printing out in correct order -
i'm new threads in c. program need declare thread pass in loop thats meant print out printfs thread.
i can't seem print in correct order. here's code:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define num_threads 16 void *thread(void *thread_id) { int id = *((int *) thread_id); printf("hello thread %d\n", id); return null; } int main() { pthread_t threads[num_threads]; (int = 0; < num_threads; i++) { int code = pthread_create(&threads[i], null, thread, &i); if (code != 0) { fprintf(stderr, "pthread_create failed!\n"); return exit_failure; } } return exit_success; } //gcc -o main main.c -lpthread
that's classic example of understanding multi-threading. threads running concurrently, scheduled os scheduler. there no such thing "correct order" when talking running in parallel.
also, there such thing buffers flushing stdout output. means, when "printf" something, not promised happen immediately, after reaching buffer limit/timeout.
also, if want work in "correct order", means wait until first thread finishes it's work before staring next one, consider using "join": http://man7.org/linux/man-pages/man3/pthread_join.3.html
upd: passing pointer thread_id incorrect in case, thread may print id doesn't belong him (thanks kevin)
Comments
Post a Comment