C++11 thread
创始人
2024-01-29 04:11:37

目录

线程thread

主要成员函数

简单线程的创建 

线程封装 

zero_thread.h

zero_thread.cpp

main.cpp


C/C++Linux服务器开发/后台架构师【零声教育】-学习视频教程-腾讯课堂

线程thread

std::thread 在 #include 头文件中声明,因此使用 std::thread 时需要包含 #include 头文件。

#include // 头文件

std::thread(...)

主要成员函数

get_id()
获取线程ID,返回类型std::thread::id对象。
http://www.cplusplus.com/reference/thread/thread/get_id/


joinable()
判断线程是否可以加入等待
http://www.cplusplus.com/reference/thread/thread/joinable/


join()
等该线程执行完成后才返回。
http://www.cplusplus.com/reference/thread/thread/join/


detach()

        detach调用之后,目标线程就成为了守护线程,驻留后台运行,与之关联的std::thread对象失去对目标线程的关联,无法再通过std::thread对象取得该线程的控制权。当线程主函数执行完之后,线程就结束了,运行时库负责清理与该线程相关的资源。

        调用 detach 函数之后:
        *this 不再代表任何的线程执行实例。
        joinable() == false
        get_id() == std::thread::id()
http://www.cplusplus.com/reference/thread/thread/detach/

简单线程的创建 

1. 传入0个值
2. 传入2个值
3. 传入引用
4. 传入类函数
5. detach
6. move 
#include 
#include 
using namespace std;// 1 传入0个值
void func1()
{cout << "func1 into" << endl;
}// 2 传入2个值
void func2(int a, int b)
{cout << "func2 a + b = " << a + b << endl;
}void func2_1(int a, int b)
{cout << "func2_1 a + b = " << a + b << endl;
}int func2_1(string a, string b)
{cout << "func2_1 a + b = " << a << b << endl;return 0;
}// 3 传入引用
void func3(int& c) // 引用传递
{cout << "func3 c = " << &c << endl;c += 10;
}//4. 传入类函数
class A
{
public:   void func4(int a){//阻塞当前线程执行,至少经过指定的 sleep_durationstd::this_thread::sleep_for(std::chrono::seconds(1));cout << "thread:" << name_ << ", fun4 a = " << a << endl;}void func4(string str){阻塞当前线程执行,至少经过指定的 sleep_duration//std::this_thread::sleep_for(std::chrono::seconds(1));cout << "thread:" << name_ << ", fun4 str = " << str << endl;}void setName(string name) {name_ = name;}void displayName() {cout << "this:" << this << ", name:" << name_ << endl;}void play(){std::cout << "play call!" << std::endl;}
private:string name_;
};//5. detach
void func5()
{cout << "func5 into sleep " << endl;std::this_thread::sleep_for(std::chrono::seconds(1));cout << "func5 leave " << endl;
}// 6. move
void func6()
{cout << "this is func6 !" << endl;
}int main()
{// 1 传入0个值cout << "\n\n main1--------------------------\n";std::thread t1(func1);	// 只传递函数t1.join();// 2 传入2个值cout << "\n\n main2--------------------------\n";int a =10;int b =20;std::thread t2(func2, a, b); // 加上参数传递,可以任意参数t2.join();std::thread t2_1((void(*)(int, int)) func2_1, a, b); // 加上参数传递,可以任意参数t2_1.join();std::thread t2_2((int(*)(string, string)) func2_1, "darren", " and mark"); // 加上参数传递,可以任意参数t2_2.join();// 3. 传入引用cout << "\n\n main3--------------------------\n";int c =10;std::thread t3(func3, std::ref(c)); // std::ref 加上参数传递,可以任意参数t3.join();cout << "main3 c = " << &c << ", "<setName("kaka");std::thread t41((void(A::*)(int)) & A::func4, a4_ptr, 100);      // 重载void func4(int a)t41.join();delete a4_ptr;//重载cout << "\n\n main4--------------------------\n";A* a4_ptr_2 = new A();a4_ptr_2->setName("king");std::thread t42((void(A::*)(string)) & A::func4, a4_ptr_2, "king"); // 重载 int func4(string str)t42.join();delete a4_ptr_2;//   5.detachcout << "\n\n main5--------------------------\n";std::thread t5(func5);  // 只传递函数t5.detach();  // 脱离cout << "pid: " << t5.get_id() << endl; // t5此时不能管理线程了cout << "joinable: " << t5.joinable() << endl; // false 判断线程是否可以加入等待//t5.join();出错std::this_thread::sleep_for(std::chrono::seconds(2)); // 如果这里不休眠会怎么样cout << " main5 end\n";// 6.movecout << "\n\n main6--------------------------\n";int x = 10;thread t6_1(func6);thread t6_2(std::move(t6_1)); // t6_1 线程失去所有权t6_1.join();  // 抛出异常   after throwing an instance of 'std::system_error't6_2.join();return 0;
}

 

线程封装 

zero_thread.h

#ifndef ZERO_THREAD_H
#define ZERO_THREAD_H
#include class ZERO_Thread
{
public:ZERO_Thread(); // 构造函数virtual ~ZERO_Thread(); // 析构函数bool start();void stop();bool isAlive(); // 线程是否存活.std::thread::id id() { return th_->get_id(); }std::thread* getThread() { return th_; }void join();  // 等待当前线程结束, 不能在当前线程上调用void detach(); //能在当前线程上调用
protected:void threadEntry();virtual void run() = 0; // 运行
protected:bool  running_; //是否在运行std::thread *th_;
};#endif // ZERO_THREAD_H

zero_thread.cpp

#include "1-2-zero_thread.h"
#include 
#include 
#include 
ZERO_Thread::ZERO_Thread():running_(false), th_(NULL)
{}ZERO_Thread::~ZERO_Thread()
{if(th_ != NULL){//如果到调用析构函数的时候,调用者还没有调用join则触发detach,此时是一个比较危险的动作,用户必须知道他在做什么if (th_->joinable()){std::cout << "~ZERO_Thread detach\n";th_->detach();}delete th_;th_ = NULL;}std::cout << "~ZERO_Thread()" << std::endl;
}bool ZERO_Thread::start()
{if (running_){return false;}try{th_ = new std::thread(&ZERO_Thread::threadEntry, this);}catch(...){throw  "[ZERO_Thread::start] thread start error";}return true;
}void ZERO_Thread::stop()
{running_ = false;
}bool ZERO_Thread::isAlive()
{return running_;
}void ZERO_Thread::join()
{if (th_->joinable()){th_->join();  // 不是detach才去join}
}void ZERO_Thread::detach()
{th_->detach();
}void ZERO_Thread::threadEntry()
{running_ = true;try{run();   // 函数运行所在 调用子类的run函数}catch (...){running_ = false;throw;}running_ = false;
}

main.cpp

#include 
#include 
#include "1-2-zero_thread.h"
using namespace std;class A: public ZERO_Thread
{
public:void run(){while (running_){cout << "print A " << endl;std::this_thread::sleep_for(std::chrono::seconds(5));}cout << "----- leave A " << endl;}
};class B: public ZERO_Thread
{
public:void run(){while (running_){cout << "print B " << endl;std::this_thread::sleep_for(std::chrono::seconds(2));}cout << "----- leave B " << endl;}
};int main()
{{A a;a.start();B b;b.start();std::this_thread::sleep_for(std::chrono::seconds(5));a.stop();a.join(); // join之前不去stopb.stop();b.join();  // 需要我们自己join}cout << "Hello World!" << endl;return 0;
}

相关内容

热门资讯

埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
平遥古城在哪 平遥古城基本现状 城垣恢宏,雉堞连云市井街巷,店肆林立四合院落,青砖瓦屋这里是平遥古城历经千年沧桑而古朴宛然,风姿依旧...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
脚上的穴位图 脚面经络图对应的... 人体穴位作用图解大全更清晰直观的标注了各个人体穴位的作用,包括头部穴位图、胸部穴位图、背部穴位图、胳...
长白山自助游攻略 吉林长白山游... 昨天介绍了西坡的景点详细请看链接:一个人的旅行,据说能看到长白山天池全凭运气,您的运气如何?今日介绍...
猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...
世界上最漂亮的人 世界上最漂亮... 此前在某网上,选出了全球265万颜值姣好的女性。从这些数量庞大的女性群体中,人们投票选出了心目中最美...
埃菲尔铁塔在哪 中国仿建埃菲尔... 2019年4月26日,广西南宁市,街头惊现一座巨型山寨版埃菲尔铁塔,高约20米,白色塔身,造型逼真,...
平遥古城在哪 平遥古城基本现状 城垣恢宏,雉堞连云市井街巷,店肆林立四合院落,青砖瓦屋这里是平遥古城历经千年沧桑而古朴宛然,风姿依旧...
苗族的传统节日 贵州苗族节日有... 【岜沙苗族芦笙节】岜沙,苗语叫“分送”,距从江县城7.5公里,是世界上最崇拜树木并以树为神的枪手部落...
北京的名胜古迹 北京最著名的景... 北京从元代开始,逐渐走上帝国首都的道路,先是成为大辽朝五大首都之一的南京城,随着金灭辽,金代从海陵王...