c++创建两个线程
在C++中,可以使用std::thread类来创建和管理线程。下面是一个示例代码,展示了如何创建两个线程:
#include <iostream>
#include <thread>
// 线程函数1
void threadFunc1() {
std::cout << "Thread 1 executing" << std::endl;
}
// 线程函数2
void threadFunc2() {
std::cout << "Thread 2 executing" << std::endl;
}
int main() {
// 创建线程1
std::thread t1(threadFunc1);
// 创建线程2
std::thread t2(threadFunc2);
// 等待线程1和线程2执行完毕
t1.join();
t2.join();
return 0;
}
在这个示例中,我们定义了两个线程函数threadFunc1和threadFunc2,分别用来执行线程1和线程2的任务。在main函数中,我们创建了两个线程t1和t2,并分别传入对应的线程函数。然后我们使用join函数来等待这两个线程执行完毕。
运行这个程序,你会看到输出中交替出现"Thread 1 executing"和"Thread 2 executing",表明两个线程在同时执行
原文地址: https://www.cveoy.top/t/topic/hysl 著作权归作者所有。请勿转载和采集!