Linux命令行运行多线程程序 和 QT集成IDE下运行多线程程序的问题。

本文共分为两个部分,第一部分说明命令行形式下运行多线程程序。第二部分介绍 QT集成IDE下多线程程序的运行。

第一部分: Linux命令行形式下运行多线程程序

在linux命令行下编译多线程程序时,需要添加 -lpthread,现在通过实验来说明命令行下的多线程程序运行:

实验中使用的程序代码如下:

#include <iostream>
#include <thread>
#include <chrono>
 
void foo()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
void bar()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    std::cout << "starting first helper...\n";
    std::thread helper1(foo);
 
    std::cout << "starting second helper...\n";
    std::thread helper2(bar);
 
    std::cout << "waiting for helpers to finish..." << std::endl;
    helper1.join();
    helper2.join();
 
    std::cout << "done!\n";
}

未添加-lpthread的运行命令:

g++ 3.cpp

运行结果出错:

/tmp/ccOfil6u.o:在函数‘std::thread::thread<void (&)()>(void (&)())’中:
3.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEEEOT_DpOT0_]+0x2f):对‘pthread_create’未定义的引用
collect2: error: ld returned 1 exit status

添加 -lpthread的运行命令:

g++ 3.cpp -lpthread

运行结果;

starting first helper...
starting second helper...
waiting for helpers to finish...
done!

第二部分: 使用QT集成IDE进行多线程程序的运行

此部分分为两个小节。 第一小节 。 第二小节使用cmake编译程序。

   1 使用qmake编译程序

  为了避免出现命令行编译时出现上述的线程问题,我们的解决方法如下:

打开项目的 .pro文件, 在文件中输入 LIBS += -lpthread 即可 。注意: 在qmake下存在.pro文件。 cmake编译下是不存在这个文件的。

2 cmake 编译程序

在CMakeLists.txt文件中添加

set(CMAKE_CXX_FLAGS " -std=c++11 -march=native -O3 -pthread" )

就可以解决上述出现的问题。

猜你喜欢

转载自blog.csdn.net/qq_40641575/article/details/84849192