单线程打印 [英] Print in single Pthread

查看:52
本文介绍了单线程打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 C 中的 Pthreads 实现一个程序.现在,我尝试让单个线程打印Hi":

I'm trying to implement a program using Pthreads in C. Now, I've tried to let a single thread print "Hi":

void * generator(void *arguments){
     printf("Hi");
     return NULL;
}

int main(int argc, const char* argv[]){
     pthread_create(&threads_ids[0], NULL, &generator, NULL);=
}

这不起作用,也不会打印任何内容.但是,当我将 pthread 的创建放在 for 循环中时,它确实会打印Hi",但每次执行时出现的情况都不同.

This doesn't work and doesn't print anything. However, when I put the creation of the pthread in a for loop it does print "Hi", but at each execution the occurrence differs.

这是正常行为吗,如果是的话;我该如何解决?提前致谢!

Is this normal behaviour, and if so; how can I fix it? Thanks in advance!

推荐答案

这是因为您的主线程返回并因此退出进程.这意味着您创建的线程永远没有机会运行.

It's because your main thread returns and thus exits the process. It means the thread you created never gets a chance to run.

与从 main() 返回不同的是,从 main() 调用 pthread_exit(0) 会让另一个线程继续执行.

Unlike just returning from main(), calling pthread_exit(0) from main(), will let the other thread continue executing.

或者,您可以通过在您创建的线程上调用 pthread_join() 来等待线程完成执行.

Alternatively, you can wait for the thread to complete execution by calling pthread_join() on the thread you created.

当您在循环中执行时,您创建的某些线程可能会在主线程退出之前执行,因此似乎工作"(打印一些 Hi).但它确实与您发布的代码存在相同的问题.

When you execute in a loop, probably some of the threads you create gets executed before main thread exits, and thus appears to "work" (prints some Hi). But it does have the same problem as the code you posted.

这篇关于单线程打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆