目录
线程thread
主要成员函数
简单线程的创建
线程封装
zero_thread.h
zero_thread.cpp
main.cpp
C/C++Linux服务器开发/后台架构师【零声教育】-学习视频教程-腾讯课堂
线程thread
std::thread 在 #include 头文件中声明,因此使用 std::thread 时需要包含 #include 头文件。
#include <thread> // 头文件
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 <iostream>
#include <thread>
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_duration
std::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 << ", "<<c << endl;
//4. 传入类函数
//重载
cout << "\n\n main4--------------------------\n";
A * a4_ptr = new A();
a4_ptr->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.detach
cout << "\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.move
cout << "\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 <thread>
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 <sstream>
#include <iostream>
#include <exception>
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 <iostream>
#include <chrono>
#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之前不去stop
b.stop();
b.join(); // 需要我们自己join
}
cout << "Hello World!" << endl;
return 0;
}