2016-09-30 59 views
3

我對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 
+0

這是一個錯誤的期望。線程啓動/執行順序不需要與創建順序相同。 –

+0

這是一個很好的'pthread'教程:https://computing.llnl.gov/tutorials/pthreads/ – yano

回答

3

這是理解多線程的經典示例。 線程正在並行運行,由OS調度程序調度。 當我們談論並行運行時,沒有「正確的順序」這樣的東西。

此外,有這樣的事情緩衝區刷新stdout輸出。意思是,當你「打印」某些東西時,並不承諾它會立即發生,但在達到某個緩衝區限制/超時之後。

另外,如果你想要做的工作,在「正確的順序」,是指等到第一個線程完成它的工作盯着在下單前,請考慮使用「連接」: http://man7.org/linux/man-pages/man3/pthread_join.3.html

UPD: 傳球指向thread_id的指針在這種情況下也是不正確的,因爲線程可能會打印不屬於他的id(謝謝凱文)

+0

那麼它的罰款是以隨機順序打印?我假設我在函數的參數中傳遞的'i'值有問題。 –

+0

是的,這將是你的情況通常的行爲。如果你願意,可以嘗試使用「連接」技術(這將不再平行) –

+0

我添加了「(void)pthread_join(threads [i],NULL);」之後「int code = ...」,它的工作!謝謝Eric Eric。 –