在 C++ 中,你可以使用 <thread> 头文件中提供的类来创建和管理线程。以下是一个简单的示例代码,演示了如何在 C++ 中创建和运行线程:
#include <iostream>
#include <thread>
// 线程函数,打印一条消息
void printMessage(const std::string& message) {
std::cout << "Thread ID: " << std::this_thread::get_id() << " Message: " << message << std::endl;
}
int main() {
// 创建一个线程,并传递一个字符串参数
std::thread t1(printMessage, "Hello from thread!");
// 等待线程执行完成
t1.join();
// 在主线程中继续执行
std::cout << "Main thread ID: " << std::this_thread::get_id() << std::endl;
std::cout << "Thread finished!" << std::endl;
return 0;
}
在这个示例中,我们首先定义了一个线程函数 printMessage,它接受一个字符串参数并打印出线程的ID以及传入的消息。然后在 main 函数中,我们创建了一个线程 t1,并将 printMessage 函数作为线程的入口点,同时传递了一个字符串参数 "Hello from thread!"。接着我们调用了 t1.join() 来等待线程 t1 执行完成。最后在主线程中打印出主线程的ID以及一条消息。
运行这个程序,你会看到输出类似以下内容:
Thread ID: [Thread ID] Message: Hello from thread!
Main thread ID: [Main thread ID]
Thread finished!
其中,[Thread ID] 和 [Main thread ID] 是线程的实际ID,它们在每次运行时都会有所不同。