创建的线程很慢

标签 c multithreading pthreads

我遇到了 pthread_create 函数的奇怪行为。代码如下:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

void *foo( void* a) {
    printf("Doing something");
    pthread_exit(NULL);
}

int main() {
    printf("Main created");
    pthread_t thread;
    pthread_create( &thread, NULL, foo, NULL );

    while(1); // This causes trouble

    pthread_join( thread, NULL );

    return 0;
}

出于某种原因,使用 while 后,来自线程的消息会在很长的延迟后显示。我希望在 pthread_create 调用后新线程完全独​​立于 main,因此不应受其代码影响。

最佳答案

这与线程无关。

你会发现同样的行为发生在:

printf("Doing something");
while(1) ;

这是因为您没有在打印的字符串末尾包含换行符,这导致该行被缓冲。由于没有进一步的输出生成,该行可能会缓冲很长时间(甚至可能永远)。

为避免这种情况,您可以:

  • 向所有输出行添加换行符,例如printf("做某事\n");

  • printf()之后调用fflush(stdout)强制刷新行

  • 预先调用 setvbuf(stdout, NULL, _IONBF, 0) 以禁用所有输出缓冲

关于创建的线程很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43811550/

相关文章:

c - 终止具有临界区代码的 POSIX 多线程应用程序的最佳方法是什么?

c - 如何存储fscanf以逆序打印?

c++ - 从线程中获取 native 句柄?

c - 为什么 "Build Project"在 Eclipse Helios CDT 中显示为灰色,即使生成文件和源代码存在?

Android Looper 和 Thread 似乎不起作用

Java多线程打印奇数和偶数

c - 如何正确使用 sem_timedwait()

c++ - 除非链接到 pthreads,否则不会出现死锁?

java - 如何在 Java 代码中使用 OpenMP?

c - 为什么这段代码返回 "Segmentation fault"错误?