多线程调用类的成员变量或者说类的内部调用多线程问题--及公共资源竞争安全的问题

多线程调用类的成员变量或者说类的内部调用多线程的方式:
方式一:
在类的内部声明如下两个函数:
//将线程函数定义为类的成员函数
void processThread(int val);//线程实际执行功能段代码
std::thread memberThread(int val)
{ return std::thread(&CImgFileFunc::processThread, this, val);}
//调用线程并返回线程

外部调用时,类的对象调用上述声明第二个函数即可:
thread t0 = imgfileObj.memberThread(0);
t0.join();//当然也可以不再定义一个线程t0,不定义则无法使用join()功能。

方式二:
在类的内部声明定义如下三个函数:
//将线程函数定义为类的成员函数
void processThread(int val);//线程实际执行功能段代码
void TestFunc(); //启动线程的入口函数
static int ThreadFunc(void* pParam,int val);
void CImgFileFunc::TestFunc()
{
thread t0(ThreadFunc,this, 0);
thread t1(ThreadFunc, this, 1);
thread t2(ThreadFunc, this, 2);
thread t3(ThreadFunc, this, 3);
thread t4(ThreadFunc, this, 4);
thread t5(ThreadFunc, this, 5);
thread t6(ThreadFunc, this, 6);
thread t7(ThreadFunc, this, 7);
t0.join();
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
t6.join();
t7.join();
}
int CImgFileFunc::ThreadFunc(void* pParam, int val)
{
CImgFileFunc* pthread = (CImgFileFunc*)pParam;
pthread->processThread(val);
return 0;
}
在类的外部调用时候,仅需要类的对象调用 对象.TestFunc();函数即可。

附注:
在类的内部多线程执行了公共的函数在调用公共变量时候会存在竞争的情况,需要使用互斥对象mutex g_mutex;//互斥对公共变量进行保护!
g_mutex.lock();
。。。公共对象的处理
g_mutex.unlock();
同时要注意,此时,类的成员变量也是公共变量,在多线程的的处理过程中可能存在影响,在 void processThread(int val);//线程实际执行功能段代码
中使用到类的成员变量时候在该段函数内部 定义局部变量并获得类的成员变量的值,在赋值过程中调用
g_mutex.lock();
。。。局部对象与类的成员变量的赋值
g_mutex.unlock();
以避免结果混乱!!!

猜你喜欢

转载自blog.csdn.net/monk1992/article/details/82866321