问题描述
背景: 如果我不使用任何线程或仅生成1个线程,这似乎可以很好地工作,这会更加令人困惑。
Clion项目here
问题: 我建立了一个基本的示例项目,该项目启动2个线程,并从主线程,线程2和线程3向控制台进行一些打印。
#include <iostream>
#include <thread>
void thread1()
{
for(int i = 0; i < 10000; i++)
{
std::cout << "thread1" << std::endl;
}
}
void thread2()
{
for(int i = 0; i < 10000; i++)
{
std::cout << "thread2" << std::endl;
}
}
int main()
{
std::cout << "Hello,World!" << std::endl;
std::thread threadObj(thread1);
std::thread threadObj2(thread2);
for(int i = 0; i < 10000; i++)
{
std::cout<<"MainThread"<<std::endl;
}
threadObj.join();
std::cout<<"Exit of Main function"<<std::endl;
return 0;
}
使用以下语言进行编译:
--coverage -pthread -g -std=gnu++2a
当我使用“使用Coverage运行'EvalTest'”在线索中运行时,出现以下错误:
找不到代码覆盖率数据
因此它不会生成所需的gcov文件,但是如果我注释掉以下代码行,它会很好地工作:
int main()
{
std::cout << "Hello,World!" << std::endl;
std::thread threadObj(thread1);
// std::thread threadObj2(thread2);
for(int i = 0; i < 10000; i++)
{
std::cout<<"MainThread"<<std::endl;
}
threadObj.join();
std::cout<<"Exit of Main function"<<std::endl;
return 0;
}
解决方法
需要执行threadObj.join()和threadObj2.join()。因此代码如下:
int main()
{
std::cout << "Hello,World!" << std::endl;
std::thread threadObj(thread1);
std::thread threadObj2(thread2);
for(int i = 0; i < 10000; i++)
{
std::cout<<"MainThread"<<std::endl;
}
threadObj.join();
threadObj2.join(); // need to join both thread for gcov to work properly
std::cout<<"Exit of Main function"<<std::endl;
return 0;
}