C++11 类内使用多线程,提高执行效率
C++11 <thread> 多线程
本篇code解决:
- 在类内部使用多线程,即多线程执行函数为类的成员函数
- 执行函数调用类的内部变量
- 同步问题
总体代码及思路
在 panel 类内,**Render()*时,使用静态函数 DateProcessThread(Data anyInData) 分批处理 mArrays 的数据,并在处理时,使用 panel 类的 静态成员变量 mClassStaticValue辅助, 等待多个线程处理完毕后,再继续执行。
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
class panel
{
public:
panel() {}
~panel() { delete mArrays; }
//Data
static double mClassStaticValue;
int* mArrays;
//静态线程函数
static void DateProcessThread(int i)
{
cout << "Data:"<< i << " I am a thread !" << endl;
cout << "I can process static value:" << mClassStaticValue << endl;
}
//入口函数
void Render()
{
std::vector<thread*> thrdList;
for (size_t i = 0; i < 5; i++)
{
thread* thrd = new thread(DateProcessThread, mArrays[i]);
thrdList.push_back(thrd);
}
for (auto thrd : thrdList)
{
thrd->join();
}
}
};
double panel::mClassStaticValue = 0;
void main()
{
panel tPanel;
panel::mClassStaticValue = 50;
tPanel.mArrays = new int[5];
for (size_t i = 0; i < 5; i++)
{
tPanel.mArrays[i] = i + 10;
}
tPanel.Render();
}

类内部使用多线程
线程执行函数必须定义为 static !
static void DateProcessThread(int i);
thread* thrd = new thread(DateProcessThread, mArrays[i]);
执行函数调用类的内部变量
该变量也必须被声明为 static 类型
static double mClassStaticValue;
//静态线程函数 static void DateProcessThread(int i) { cout << "Data:"<< i << " I am a thread !" << endl; cout << "I can process static value:" << mClassStaticValue << endl; }
同步问题
thread 全部创建后,再依次 join。 可实现多个线程同步跑。
事实上,thread在创建的时候就已经开始执行了,当主线程遇到join的时候会等待该线程执行完才继续往下走。
所以,先循环创建 n 个thread, n 个 thread 同步执行,等待 n个thread执行完毕。
如果,写成如下的形式,则为顺序执行,失去创建多线程的意义:
//入口函数 void Render() { //多个线程顺序执行,没有实现 采用多线程提高效率的初衷 for (size_t i = 0; i < 5; i++) { thread* thrd = new thread(DateProcessThread, mArrays[i]); thrd->join(); } }

其他参考blog
- C++多线程类Thread(C++11) https://blog.csdn.net/ouyangfushu/article/details/80199140
- C++多线程 join https://blog.csdn.net/listenalone/article/details/79639299 https://www.cnblogs.com/IGNB/p/10522252.html
- c++11 thread 类内使用方法和跨类使用方法 https://blog.csdn.net/gychixxx/article/details/78875061