【发布时间】:2021-10-02 15:59:08
【问题描述】:
我正在学习 POSIX 线程的基础知识。我想创建一个打印“Hello World!”的程序10 次,每次打印输出之间延迟一秒。我已经使用 for 循环打印了 10 次,但我一直坚持如何实现时间延迟部分。
这是我目前的代码:
#define MAX 10
void* helloFunc(void* tid)
{
printf("Hello World!\n", (int)(intptr_t)tid);
}
int main(int ac, char * argv)
{
pthread_t hej[MAX];
for (int i = 0; i < MAX; i++)
{
pthread_create(&hej[i], NULL, helloFunc, (void*)(intptr_t)i);
pthread_join(&hej[i], NULL);
}
pthread_exit(NULL);
return(0);
}
提前致谢!
【问题讨论】:
-
printf("Hello World!\n", (int)tid);无效,。要等待 1 秒,您可以使用sleep(1),不要忘记#include <unistd.h>