c++ - 为什么我的线程不在后台运行?

标签 c++ multithreading c++11 parallel-processing

在下面的 list 中,我希望在创建线程后立即调用 t.detach(),线程 t 将在后台运行而 printf("quit the main function now\n") 将被调用,然后 main 将退出。

#include <thread>
#include <iostream>

void hello3(int* i)
{

    for (int j = 0; j < 100; j++)
    {
        *i = *i + 1;
        printf("From new thread %d \n", *i);
        fflush(stdout);

    }

    char c = getchar();
 }

int main()
{
    int i;
    i = 0;
    std::thread t(hello3, &i);
    t.detach();
    printf("quit the main function now \n");
    fflush(stdout);
    return 0;
}

然而,从它在屏幕上打印出来的内容来看,情况并非如此。它打印

From new thread 1
From new thread 2
....
From new thread 99
quit the main function now.

看起来 main 函数在执行命令printf("quit the main function now\n"); 之前等待线程完成并退出。

你能解释一下这是为什么吗?我在这里缺少什么?

最佳答案

问题是你的线程太快了。

它能够在 main 有机会继续之前打印所有 100 个字符串。

尝试让线程变慢,您会在线程之前看到主要的 printf

关于c++ - 为什么我的线程不在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45700977/

相关文章:

c++ - 两个依赖类c++

c++ - QProcess:进程仍在运行时被销毁

multithreading - 如何在执行后台任务时呈现 View Controller ?

c++ - 运算符按位左移

c++ - 如何将 std::chrono::time_point 转换为 uint64_t?

c++ - 在 C++ 中转换 IP 地址的问题

c++ - 使用输出流创建的二进制输出文件的内容

c++ - 有没有办法在 unordered_map 的某个位置插入元素?

c++ - 内存排序问题

c++ - C++11 中有新的函数类型表达式格式吗?