#include <iostream>
#include <thread>
#include <vector>
using namespace std;
const int NUM_THREADS = 4;//4线程
const int MAX_COUNT = 80;//80次循环
int add(int a, int b) {
return a+b;
}//随便写的
void myTask(int thread_id) {
int start = thread_id * (MAX_COUNT / NUM_THREADS);
int end = (thread_id + 1) * (MAX_COUNT / NUM_THREADS);//平均分一下任务
//线程里面要做的事情
int c=0;int d=1;
for(int i=0;i<100;i++){
for (int i = start; i < end; i++) {
d++;
int f= add(9,9);
printf("%d\n", f);
}
c=add(5,6)+d;
}
}//起线程
int main() {
std::vector<std::thread> threads;
for (int t = 0; t < NUM_THREADS; t++) {
threads.emplace_back(myTask, t);
}
for (auto& t : threads) {
t.join();
}//调用
return 0;
}
本段代码作为一种优化for循环的简单demo,可以将for循环放在多个线程上进行处理可以提高for循环的运行速度