我正在创建一个gTEST,其中我启动了一个拥有自己的线程的服务。在停止服务之前,我创建了具有自己的线程的类的对象。现在我希望服务线程等待对象完全销毁(类线程执行它的工作并退出(,然后停止服务线程。如果我让测试睡眠一段时间,evrything运行良好。
测试.cpp
TEST_F(TestFixture, TestName) {
service->start(); //Sevice is having its own thread
// Creating the Object
DummyClass Obj(); //Object is having its own thread that starts on initialization
EXPECT_CALL(*_Mock,
Func(NotNull(), NotNull(), NotNull(), NotNull(), NotNull(), NotNull()))
.Times(1)
.WillRepeatedly(Return(1));
EXPECT_EQ(true,
Obj.Func1(a,b, c, d)
.IsOk());
usleep(1000); //If I remove the this reason-111: Connection refused.
service->Stop();
}
类.cpp
//Destructor
SasThreadHelper::~SasThreadHelper() {
this->StopThread();
}
//Called in Constructor
void SasThreadHelper::StartThread() {
if (m_thread.get_id() != std::thread::id()) {
return;
}
m_stop_thread_flag = 0;
// spawn the thread
m_thread = std::thread(&SasThreadHelper::ReadMessagesFromQueue,
this);
}
void SasThreadHelper::StopThread() {
m_client_authenticated = 0;
m_stop_sas_thread_flag = 1;
m_thread.join();
}
您可以使用join()
等待线程执行。如果你的测试类加入自己的线程,你可以在析构函数中等待线程完成,如下所示:
class WaitOnOwnThread
{
private:
std::thread t;
public:
WaitOnOwnThread(): t{[](){
std::cout << "Thread starts here" << std::endl;
sleep(2); // thread is doing something
}}
{
}
~WaitOnOwnThread()
{
t.join(); // wait that thread finishes
std::cout << "Thread has finished" << std::endl;
}
};
int main()
{
{
WaitOnOwnThread w;
std::cout << "Do some things in main thread" << std::endl;
} // end of scope for destruction of WaitOnOwnThread
std::cout << "end of main " << std::endl;
}