我想學習Unix C併爲練習做一些練習。我正在處理的當前問題涉及POSIX線程(主要是pthread_create()和pthread_join())posix線程(pthread_create和pthread_join)
該問題要求使用兩個線程重複打印「Hello World」。一個線程打印「Hello」1000次,而第二個線程打印「World」1000次。主程序/線程將在繼續之前等待兩個線程完成。
這是我現在所擁有的。
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
void *print_hello(void *arg)
{
int iCount;
for(iCount = 0; iCount < 1000; iCount++)
{
printf("Hello\n");
}
}
void *print_world(void *arg)
{
int iCount;
for(iCount = 0; iCount < 1000; iCount++)
{
printf("World\n");
}
}
int main(void)
{
/* int status; */
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, NULL, print_hello, (void*)0);
pthread_create(&thread2, NULL, print_world, (void*)0);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
這似乎沒有充分發揮作用。它按預期打印「你好」。但「世界」根本沒有印。似乎第二個線程根本沒有運行。不知道我正在使用pthread_join。正如練習所要求的,我的意圖是讓主線程「等待」這兩個線程。
任何幫助,將不勝感激。
似乎對我很好,並按預期工作。你可能想在你的線程函數的最後加上'return NULL'。 – JackOfAllTrades
要評論你的代碼,NULL通常被定義爲「(void *)0」,所以它有點愚蠢的使用兩者。我建議NULL - 不保證所有系統上的空指針都被表示爲0,而NULL將被定義爲適當的值。 –