Multithreading 防止同时运行函数
全部, 下面是我要查找的伪代码:Multithreading 防止同时运行函数,multithreading,visual-studio-2010,c++11,mutex,Multithreading,Visual Studio 2010,C++11,Mutex,全部, 下面是我要查找的伪代码: class A : public Base { public: virtual int func(); virtual int other_func(); }; class B : public Base { public: virtual int func(); virtual int other_func(); }; class MainFrame { public: MainFrame(); Base *
class A : public Base
{
public:
virtual int func();
virtual int other_func();
};
class B : public Base
{
public:
virtual int func();
virtual int other_func();
};
class MainFrame
{
public:
MainFrame();
Base *CreateObject();
int StartThread();
int SomeOtherFunc();
private:
Base *m_base;
};
MainFrame::MainFrame()
{
m_base = NULL;
}
Base *MainFrame::CreateObject()
{
if( <condition1> )
m_base = new A();
else
m_base = new B();
}
int MainFrame::StartThread()
{
int result;
while( !TestDestroy() )
{
result = m_base->func();
Sleep( 5000 );
}
}
int MainFrame::SomeOtherFunc()
{
m_base->other_func();
}
A类:公共基地
{
公众:
虚int func();
虚int other_func();
};
B类:公共基地
{
公众:
虚int func();
虚int other_func();
};
类主机
{
公众:
大型机();
Base*CreateObject();
int StartThread();
int SomeOtherFunc();
私人:
基地*m_基地;
};
大型机::大型机()
{
m_base=NULL;
}
基本*大型机::CreateObject()
{
如果()
m_base=新A();
其他的
m_base=新的B();
}
int大型机::StartThread()
{
int结果;
而(!TestDestroy())
{
结果=m_base->func();
睡眠(5000);
}
}
int MainFrame::SomeOtherFunc()
{
m_base->other_func();
}
简而言之:我有两个类a和B,它们都是从同一个基类派生的。它们都有两个从基函数重新定义的函数(实际上要多得多,但这并不重要)。每个类都位于自己的DLL中
我还有一个主GUI应用程序,它根据某些条件调用a或B的方法。它还可以在某个时间点生成线程。在线程中,程序调用a/B类函数
现在我要做的是在func()执行时防止执行其他的函数
我可能应该使用互斥,但现在的问题是-我该如何设计它?我应该在函数本身内部实例化互斥体还是在大型机方法内部的调用上实例化互斥体?在这种情况下,互斥体必须是全局变量吗?它可以是基类的成员吗
同样,从辅助线程进行的func()调用应该停止对Base的任何其他方法的调用,直到调用完成
蒂亚
这是用C++11/MSVC 2010/gcc5.4编写的
[编辑]:
有关示例,请参见以下内容,并将其与以下代码进行比较:
std::mutex my_mutex;
int MainFrame::StartThread()
{
int result;
while( !TestDestroy() )
{
std::lock_guard<std::mutex> locker( my_mutex );
result = m_base->func();
Sleep( 5000 );
}
}
int MainFrame::SomeOtherFunc()
{
std::lock_guard<std::mutex> locker( my_mutex );
m_base->other_func();
}
std::mutex my_mutex;
int大型机::StartThread()
{
int结果;
而(!TestDestroy())
{
std::锁紧防护柜(我的互斥锁);
结果=m_base->func();
睡眠(5000);
}
}
int MainFrame::SomeOtherFunc()
{
std::锁紧防护柜(我的互斥锁);
m_base->other_func();
}
这两种解决方案之间有什么区别吗?它们是否都适用于我的目的-以独占方式运行线程功能,防止执行任何其他A/B功能
[/EDIT]您需要添加某种类型的同步(例如互斥)。要么在线程中,要么在函数中。@Someprogrammerdude,我把它放在哪里重要吗?例如,在StartThread()/SomeOtherFunc()内部还是在函数本身中?有区别吗?线程应该使用单个互斥对象进行同步。这个对象是如何定义的——全局的、作为静态成员的、作为指向同一互斥体的成员指针的——完全取决于您。@Tsyvarev,我所描述的是线程同步还是函数同步?因为一个函数在一个线程中运行这一事实并不那么重要——我只需要它在线程中运行,这样就不会阻塞主GUI,而且应用程序的逻辑也会阻塞主GUI。我可以在计时器事件上运行它,或者通过其他方式运行它。另外,请参阅我刚才在OP上所做的编辑。如果数据库连接由
Base
类的静态成员管理,那么这听起来是合理的。