gcov无法与pthreads,WSL-2,Clion一起使用

问题描述

背景: 如果我不使用任何线程或仅生成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'”在线索中运行时,出现以下错误:

找不到代码覆盖率数据

enter image description here

因此它不会生成所需的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;
}

enter image description here

解决方法

需要执行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;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...