我不知道什麼是錯與下面的程序,但它不會打印每一個語言一次,但隨機一些更多的時候,多一些少一些不會打印併發與並行線程,一個典型的錯誤行爲
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
char *messages[] = {
"English: Hello World!",
"French: Bonjour, le monde!",
"Spanish: Hola al mundo",
"Klingon: Nuq neH!",
"German: Guten Tag, Welt!",
"Russian: Zdravstvytye, mir!",
"Japan: Sekai e konnichiwa!",
"Latin: Orbis, te saluto!"
};
#define NUM_MESSAGES (sizeof(messages)/sizeof(char*))
void *PrintHello(void *messageid)
{
pthread_t taskid;
int *id_ptr, message_num;
taskid = pthread_self();
printf("This is thread with ID %lu.\n", taskid);
message_num = *((int *) messageid);
printf("%s \n", messages[message_num]);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_MESSAGES];
int rc, i;
for(i = 0; i < NUM_MESSAGES; i++) {
void * argument = (void*) &i;
rc = pthread_create(&threads[i], NULL, PrintHello, argument);
if(rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for(i = 0; i < NUM_MESSAGES; i++) {
pthread_join(threads[i], NULL);
}
pthread_exit(NULL);
}
我想這個問題在某種程度上與參數指針有關。我試圖鎖定不同的部分,但沒有成功。
謝謝您的幫助。這對我有效。有沒有試圖用鎖來解決這個問題?我在設置「參數」之前嘗試鎖定,並在線程創建後解鎖,但沒有工作:/我知道這將是協調的想法,但只是爲了我的利益:) – smoes 2012-07-10 07:08:49
@smoes不,鎖定在這裏是不可行的。一旦你通過了停止使用'i'的點,你將不得不在創建線程和解鎖線程之前以某種方式鎖定。 – cnicutar 2012-07-10 07:10:43
@smoes,不使用pthread mutexes - pthread mutexes必須由鎖定它們的同一個線程釋放,但在這裏您需要等待另一個線程在解鎖之前捕獲該值。而且,通過只讓一個線程立即運行,你就失去了線程的很多好處。通常的解決方案是爲每個線程分配一個新的緩衝區,然後將其傳遞給pthread_create。新線程然後負責釋放緩衝區。這種方式不需要鎖。 – bdonlan 2012-07-10 07:11:34