注:本代码是在VS2019编译器上运行的。
以下所有代码都在同一个CPP里。
顺序是从上到下的。按照这个顺序赋值代码块粘贴到cpp里就完全OK。
头文件
#include <windows.h>
#include <iostream>
#include <map>
#include <vector>
#include <thread>
#include <mutex>
#include <fstream>
#include <unordered_map>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <variant>
全局变量
std::mutex theMutex;
using uLock = std::unique_lock<std::mutex>;
void ShowBigAndSmallNumber(int iBigNumber, int iSmallNumber) {
std::cout << "模块::" << iBigNumber << ",id是::" << iSmallNumber << std::endl;
}
类的定义 成员 和 函数
class MyClass {
public:
MyClass() {}
~MyClass() {}
MyClass(int iBigIndex);
void FomrBigMap();
private:
int iBigIndex = -1;
};
MyClass::MyClass(int iBigIndex) {
this->iBigIndex = iBigIndex;
}
void MyClass::FomrBigMap() {
for (int index = 1; index <= 200; index++) {
Sleep(50); //先sleep50ms,方便观察,以免单个线程抢占太多
uLock lock(theMutex);
ShowBigAndSmallNumber(this->iBigIndex, index);
}
Sleep(3 * 1000);
std::cout << "" << std::endl;
std::cout << "模块::" << this->iBigIndex << "执行完毕" << std::endl;
std::cout << "" << std::endl;
}
主函数
void main() {
std::vector<std::pair<MyClass*, std::thread*>> vecConTextAndThread;
for (size_t index = 1; index <= 10; index++) {
MyClass* newClass = new MyClass(index);
vecConTextAndThread.push_back(std::pair<MyClass*, std::thread*>(newClass ,new std::thread(&MyClass::FomrBigMap, newClass)) );
}
//下面这个For循环,会等到所有线程都运行完毕,才会继续走for循环下面的部分。
for (size_t index = 0; index < vecConTextAndThread.size(); index++) {
if (vecConTextAndThread[index].second != nullptr) {
if (vecConTextAndThread[index].second->joinable() == true) {
vecConTextAndThread[index].second->join();
std::cout << "线程id::" << (index + 1) << "join" << std::endl;
}
}
}
std::cout << "所有线程执行完毕" << std::endl;
//将堆中的数据清除
for (size_t index = 0; index < vecConTextAndThread.size(); index++) {
if (vecConTextAndThread[index].first != nullptr) {
delete vecConTextAndThread[index].first;
vecConTextAndThread[index].first = nullptr;
}
if (vecConTextAndThread[index].second != nullptr) {
delete vecConTextAndThread[index].second;
vecConTextAndThread[index].second = nullptr;
}
}
system("pause");
}
以下是打印结果。