用C++来写一个多线程案例
时间: 2023-12-31 17:06:20 浏览: 35
当然可以!以下是一个使用C++编写的简单多线程案例,其中创建了两个线程来执行不同的任务:
```cpp
#include <iostream>
#include <thread>
// 任务1:计算阶乘
void calculateFactorial(int n) {
int factorial = 1;
for (int i = 1; i <= n; ++i) {
factorial *= i;
}
std::cout << "Factorial of " << n << " is: " << factorial << std::endl;
}
// 任务2:打印一组数字
void printNumbers(int start, int end) {
for (int i = start; i <= end; ++i) {
std::cout << i << " ";
}
std::cout << std::endl;
}
int main() {
// 创建线程并执行任务
std::thread t1(calculateFactorial, 5);
std::thread t2(printNumbers, 1, 10);
// 主线程等待两个子线程执行完毕
t1.join();
t2.join();
return 0;
}
```
在上面的示例中,`calculateFactorial`函数计算给定数字的阶乘,`printNumbers`函数用于打印一组数字。`main`函数中创建了两个线程`t1`和`t2`,并分别将任务1和任务2分配给它们执行。使用`std::thread`类来创建线程,并通过参数传递给函数所需的参数。最后,主线程使用`join`函数等待两个子线程完成执行。
编译并运行这个程序,你会看到如下输出:
```
Factorial of 5 is: 120
1 2 3 4 5 6 7 8 9 10
```
这个例子演示了如何使用C++创建多线程,并同时执行不同的任务。当然,你可以根据自己的需求进行修改和扩展。