在C中运行并发线程?

jer*_*h91 0 c concurrency multithreading

我正在测试在C中运行并发线程的行为,使用无限运行的线程函数.我的问题是为什么不在下面的代码中,"你好!!!" 得到印刷?我以为pthread_create()被调用然后立即进入循环的下一次迭代,为什么代码等待第一个pthread_create()完成?是不是应该同时运行多个线程?

void main(int argc, char **argv)
{
    pthread_t tid;
    int i;

    //Create 4 inf threads
    for (i=0;i< 4;i++)
    {
        //printf("hello!\n");
        //pthread_create(&tid, NULL, thread_incr, (void *)i);
        pthread_create(&tid, NULL, t_nostop, (void *)i);
        printf("HELLO!!!"); //This linen is NEVER printed!!
    }

    pthread_exit(NULL);
}

void* t_nostop(void * argp)
{
    int i=1;
    int t_num=(int) argp;
    while(i==1){t_num++;}

}
Run Code Online (Sandbox Code Playgroud)

sim*_*onc 6

多个线程应该同时运行.这应该在你的代码中发生.

我猜测printf调用已执行但不立即生成输出.控制台输出可能是行缓冲的,因此只有在打印换行符或刷新时才会显示.

尝试\n在您打印的字符串末尾添加或在添加fflush(stdout)后添加printf.

编辑:关于行缓冲的评论...
当标准C库决定控制台写入相对昂贵并且只应尝试连贯的文本块时,会发生行缓冲 .相干块的一个简单定义是一条线.当它等待输入换行符时,C lib将printf调用内容存储在一块内存中,追加后续的printfs