C++中的并发线程初接触
当我想要用另一个线程实现hello world函数时
mian.c函数
#include <iostream>
#include <thread>
using namespace std;
void hello()
{
cout<<"hello concurrent world\n";
}
int main()
{
thread t(hello);
cout<<"hello world"<<endl;
t.join();
}
对于应用程序来说,该程序启动了一个全新的线程来实现,将线程数量一分为二初始线程是main(),而新线程由std::thread对象构造函数指定的hello()函数开始。t.join函数的作用在于初始线程等待新线程结束.
报错如下信息:
CMakeFiles/template.dir/main.cpp.o:在函数‘std::thread::thread<void (&)()>(void (&)())’中:
/usr/include/c++/5/thread:137:对‘pthread_create’未定义的引用
collect2: error: ld returned 1 exit status
CMakeFiles/template.dir/build.make:83: recipe for target 'template' failed
make[3]: *** [template] Error 1
CMakeFiles/Makefile2:75: recipe for target 'CMakeFiles/template.dir/all' failed
make[2]: *** [CMakeFiles/template.dir/all] Error 2
CMakeFiles/Makefile2:82: recipe for target 'CMakeFiles/template.dir/rule' failed
make[1]: *** [CMakeFiles/template.dir/rule] Error 2
Makefile:118: recipe for target 'template' failed
make: *** [template] Error 2
原因:
原来使用并发线程实现时,需要在CMakelists中添加库依赖
CMakelists
cmake_minimum_required(VERSION 3.15)
project(template)
set(CMAKE_CXX_STANDARD 11)
find_package(Threads REQUIRED)
add_executable(template main.cpp)
target_link_libraries(template Threads::Threads)