作者需要用到多线程编程,找到的例程如下:
多线程编程
#include <iostream>
#include<thread>
#include<unistd.h>
using namespace std;
void sayHello()
{
while(1)
{
sleep(1);
cout<<endl<<"hello"<<endl;
}
}
void sayWorld()
{
while(1)
{
sleep(1);
cout<<endl<<"world"<<endl;
}
}
int main()
{
thread threadHello(sayHello);
thread threadWorld(sayWorld);
threadHello.join();
threadWorld.join();
return 0;
}
拿到本地后发现编译不过,报错如下:
sys-01@ubuntu:~/pro_hw/thread_cpp/build$ make
[ 50%] Building CXX object CMakeFiles/main.dir/main.cpp.o
[100%] Linking CXX executable main
CMakeFiles/main.dir/main.cpp.o: In function `std::thread::thread<void (&)()>(void (&)())':
main.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEEEOT_DpOT0_]+0x7d): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
CMakeFiles/main.dir/build.make:96: recipe for target 'main' failed
make[2]: *** [main] Error 1
CMakeFiles/Makefile2:82: recipe for target 'CMakeFiles/main.dir/all' failed
make[1]: *** [CMakeFiles/main.dir/all] Error 2
Makefile:90: recipe for target 'all' failed
make: *** [all] Error 2
经过查找得知,这是因为thread不属于std标准库,所以需要额外链接。也就是需要修改CMakeLists.txt。修改后的CMake如下:
cmake_minimum_required(VERSION 2.6)
project(Test)
add_definitions(-std=c++11)
add_definitions(-w)
add_definitions(-pthread)//修改第一处
add_executable(main main.cpp)
target_link_libraries(main pthread)//修改第二处
总共修改了两处1.添加编译参数 2.链接库文件