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

多线程调用类的成员变量或者说类的内部调用多线程的方式:
方式一:
在类的内部声明如下两个函数:
//将线程函数定义为类的成员函数
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();
以避免结果混乱!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值