c++起五个线程循环执行操作的代码
时间: 2023-08-24 11:36:18 浏览: 42
下面是一个简单的 C++ 代码片段,它创建了 5 个线程并让它们循环执行操作:
```cpp
#include <iostream>
#include <thread>
void operation(int id) {
for (int i = 0; i < 10; ++i) {
std::cout << "Thread " << id << " executing operation " << i << std::endl;
}
}
int main() {
std::thread threads[5];
// 创建 5 个线程并让它们执行操作
for (int i = 0; i < 5; ++i) {
threads[i] = std::thread(operation, i);
}
// 等待所有线程执行完毕
for (int i = 0; i < 5; ++i) {
threads[i].join();
}
return 0;
}
```
在上面的代码中,我们定义了一个名为 `operation` 的函数,它接受一个整数参数 `id`,表示当前线程的 ID。在 `operation` 函数中,我们使用一个简单的循环来模拟操作的执行。在主函数中,我们创建了 5 个线程,并让它们执行 `operation` 函数。最后,我们使用 `join` 函数等待所有线程执行完毕。
相关问题
现在我需要用5个线程执行总共100次1+1的c++代码
下面是一个使用 5 个线程执行 100 次 1+1 的 C++ 代码示例:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 定义一个互斥锁
void operation(int id) {
for (int i = 0; i < 20; ++i) {
mtx.lock(); // 加锁,防止多个线程同时操作 count
std::cout << "Thread " << id << " executing operation " << i << std::endl;
int count = 1 + 1;
std::cout << "Thread " << id << " count = " << count << std::endl;
mtx.unlock(); // 解锁
}
}
int main() {
std::thread threads[5];
// 创建 5 个线程并让它们执行操作
for (int i = 0; i < 5; ++i) {
threads[i] = std::thread(operation, i);
}
// 等待所有线程执行完毕
for (int i = 0; i < 5; ++i) {
threads[i].join();
}
return 0;
}
```
在上面的代码中,我们定义了一个名为 `operation` 的函数,它接受一个整数参数 `id`,表示当前线程的 ID。在 `operation` 函数中,我们使用一个简单的循环来模拟操作的执行,其中我们使用了一个互斥锁 `mtx` 来保护 `count` 变量的访问。在主函数中,我们创建了 5 个线程,并让它们执行 `operation` 函数。最后,我们使用 `join` 函数等待所有线程执行完毕。
c++ for循环创建线程
在 C++ 中,可以使用 for 循环来创建多个线程。以下是一个示例代码:
```cpp
#include <iostream>
#include <thread>
void threadFunction(int i) {
std::cout << "Thread " << i << " is running" << std::endl;
}
int main() {
const int numThreads = 5;
// 创建多个线程
std::thread threads[numThreads];
for (int i = 0; i < numThreads; ++i) {
threads[i] = std::thread(threadFunction, i);
}
// 等待所有线程完成
for (int i = 0; i < numThreads; ++i) {
threads[i].join();
}
return 0;
}
```
在上面的代码中,我们定义了一个 `threadFunction` 函数,它将作为每个线程的入口点。在 `main` 函数中,我们通过循环创建了多个线程,并将每个线程与 `threadFunction` 函数绑定。然后,我们使用 `join` 函数等待所有线程完成执行。
请注意,在创建线程时,我们使用了一个数组 `threads` 来存储线程对象。这是因为我们需要在后面的代码中对每个线程进行操作,例如等待线程完成。