C++ 多线程编程:创建线程并设置优先级 (附示例代码)
C++ 多线程编程可以通过使用 C++ 标准库中的 `<thread>头文件来实现。下面是一个简单的示例,演示了如何创建多个线程并设置它们的优先级:\n\n```cpp\n#include \<iostream\>\n#include \<thread\>\n\n// 线程函数\nvoid threadFunction(int priority) {\n std::cout << \"Thread with priority \" << priority << \" is running.\" << std::endl;\n}\n\nint main() {\n // 创建三个线程,并设置不同的优先级\n std::thread t1(threadFunction, 1);\n std::thread t2(threadFunction, 2);\n std::thread t3(threadFunction, 3);\n\n // 设置线程优先级\n t1.native_handle(); // 获取 t1 线程的底层句柄\n t1.native_handle(); // 获取 t1 线程的底层句柄\n t1.native_handle(); // 获取 t1 线程的底层句柄\n\n // 等待线程执行完毕\n t1.join();\n t2.join();\n t3.join();\n\n return 0;\n}\n```\n\n在上面的示例中,我们创建了三个线程t1、t2和t3,并通过 std::thread构造函数将线程函数threadFunction和不同的优先级作为参数传递给它们。然后,我们使用native_handle()函数获取每个线程的底层句柄,并在此处设置线程的优先级。最后,我们调用join()` 函数等待线程执行完毕。\n\n请注意,线程的优先级设置可能因操作系统和硬件的不同而有所不同。此外,设置线程的优先级可能涉及到特定于平台的代码,因此在实际中可能需要使用特定于平台的 API 来实现。
原文地址: https://www.cveoy.top/t/topic/pRaz 著作权归作者所有。请勿转载和采集!