我對C中的線程相當陌生。對於這個程序,我需要聲明一個線程,我將其傳遞給for循環,這意味着打印出線程中的printfs。線程沒有按正確的順序打印
我似乎無法讓它以正確的順序打印。這是我的代碼:
#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 from thread %d\n", id);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
for (int i = 0; i < 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
這是一個錯誤的期望。線程啓動/執行順序不需要與創建順序相同。 –
這是一個很好的'pthread'教程:https://computing.llnl.gov/tutorials/pthreads/ – yano