我想教自己pthreads線程。我有以下來源,編譯和運行正確:爲什麼pthread_join在本例中沒有正確關閉線程數組?
#include <stdio.h>
#include <pthread.h>
#define PTHREAD_COUNT 10
#define FREQ 5
void *thread_function(void *arg) {
int *incoming = (int *)arg;
int freqIdx;
for (freqIdx = 0; freqIdx < FREQ; freqIdx++)
fprintf(stdout, "Hello, world (thread %d)\n", *incoming);
return NULL;
}
int main(int argc, char **argv) {
pthread_t thread_IDs[PTHREAD_COUNT];
void *exit_status;
int threadIdx;
for (threadIdx = 0; threadIdx < PTHREAD_COUNT; threadIdx++) {
pthread_create(&thread_IDs[threadIdx], NULL, thread_function, &threadIdx);
pthread_join(thread_IDs[threadIdx], &exit_status);
}
return 0;
}
我得到以下結果:
Hello, world (thread 0)
Hello, world (thread 0)
Hello, world (thread 0)
Hello, world (thread 0)
Hello, world (thread 0)
Hello, world (thread 1)
...
Hello, world (thread 9)
如果我pthread_create
pthread_t
類型的數組超過一個循環,然後pthread_join
在一個單獨的循環,然後事情失敗:
#include <stdio.h>
#include <pthread.h>
#define PTHREAD_COUNT 10
#define FREQ 5
void *thread_function(void *arg) {
int *incoming = (int *)arg;
int freqIdx;
for (freqIdx = 0; freqIdx < FREQ; freqIdx++)
fprintf(stdout, "Hello, world (thread %d)\n", *incoming);
return NULL;
}
int main(int argc, char **argv) {
pthread_t thread_IDs[PTHREAD_COUNT];
void *exit_status;
int threadIdx;
/* here I split the thread _create and _join steps into separate loops */
for (threadIdx = 0; threadIdx < PTHREAD_COUNT; threadIdx++)
pthread_create(&thread_IDs[threadIdx], NULL, thread_function, &threadIdx);
for (threadIdx = 0; threadIdx < PTHREAD_COUNT; threadIdx++)
pthread_join(thread_IDs[threadIdx], &exit_status);
return 0;
}
從這個輸出是相當錯誤的。而不是從每個線程得到五個fprintf
聲明,我從線程0獲得一個或兩個來自線程2和3以及大約20到25個Hello, world
語句。
爲什麼這會失敗?