C++创建独立线程:主程序关闭后线程仍运行
#include <iostream>\n#include <thread>\n\nvoid threadFunction()\n{\n while (1); // 无限循环\n}\n\nint main()\n{\n std::thread threads[10]; // 创建十个线程\n\n // 启动十个线程\n for (int i = 0; i < 10; ++i)\n {\n threads[i] = std::thread(threadFunction);\n }\n\n // 主程序继续执行其他任务\n std::cout << "主程序执行其他任务" << std::endl;\n\n // 等待所有线程执行完成\n for (int i = 0; i < 10; ++i)\n {\n threads[i].join();\n }\n\n return 0;\n}\n在上述代码中,threadFunction函数是每个线程要执行的代码,其中的while (1)是一个无限循环。在main函数中,我们创建了十个线程,并启动它们执行threadFunction函数。然后,主程序继续执行其他任务,最后通过join函数等待所有线程执行完成。这样,即使主程序关闭,这十个线程仍然可以继续执行无限循环。
原文地址: https://www.cveoy.top/t/topic/pZmI 著作权归作者所有。请勿转载和采集!