Linux C++多线程编程学习笔记

1. thread header

#include <thread>

2. 构造函数原型

default 		 (1)	 thread() noexcept;
initialization   (2)	 template <class Fn, class... Args>
					 	 explicit thread (Fn&& fn, Args&&... args);
copy [deleted]   (3)	 thread (const thread&) = delete;
move			 (4)   	 thread (thread&& x) noexcept;

2.1 参数说明

Fn: 函数指针、成员函数指针、函数对象,如果函数有返回值,将被忽略。
args: 调用Fn函数时传递的参数,如果Fn是指向成员函数,则第一个参数应该传递该成员函数所属的对象的指针或引用

3. 创建thread对象

thread t_empty;	// 调用默认构造函数,不代表任何可执行的线程

4. 用一个函数初始化thread

#include <iostream>
#include <thread>


using namespace std;

void threadFunc()
{
    cout << "Welcome to Multithreading" << endl;
}

int main( )
{
         std::thread funcTest1(threadFunc);
         return 0;
}

运行结果:

Starting /home/rootroot/Learn/C++/MultiThread/multiThread/slamtest…

terminate called without an active exception

The program has unexpectedly finished.

/home/rootroot/Learn/C++/MultiThread/multiThread/slamtest crashed

运行出错,因为funcTest1线程没有在main函数结束前结束。

要解决此问题,可以使用 join() 函数解决。
该函数仅仅在对应线程执行结束后才会返回。

int main( )
{
         std::thread funcTest1(threadFunc);
         funcTest1.join(); // 线程结束后才会返回
         return 0;
}

join() 返回后,该线程变为 ** not joinable** ,
当线程由默认构造函数构建 或者 move/赋值给另一个线程 或者 join() or detach()成员函数被调用,在这三种情况下,此线程是不可 join() 的。

参考:

https://www.tutorialcup.com/cplusplus/multithreading.htm
http://www.cplusplus.com/reference/thread/thread/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值