C++中的并发线程(一)

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值