我想学习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将被定义为适当的值。 –