-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.hpp
More file actions
52 lines (37 loc) · 1.77 KB
/
Copy pathThread.hpp
File metadata and controls
52 lines (37 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#pragma once
#include "noncopyable.hpp"
#include <functional>
#include <thread>
#include <memory>
#include <string>
#include <atomic>
// 对线程操作的封装,可以更便捷的使用线程操作
// 线程创建,启动,等待,获取信息
class Thread : private noncopyable
{
public:
// 定义了一个线程函数类型,无返回值,无参数。
// 当需要参数输入,需要使用绑定器 ThreadFunc func = std::bind( cb, 参数)
using ThreadFunc = std::function<void()>;
// string(),调用空的构造函数,创建一个空字符串对象
explicit Thread(ThreadFunc func, const std::string &name = std::string());
~Thread();
void start(); // 启动线程
void join(); // 等待完成
bool started() const { return started_ ;} // 返回线程状态是否启动
pid_t tid() const { return tid_; } // 返回线程的 id,相当于在linux用top指令查询出来的
const std::string& name() const { return name_; } //返回线程的名字
//必须是静态成员函数,才能访问静态成员变量
static int numCreated() { return numCreadted_; } //返回创建线程数量
private:
void setDefaultName(); //设置线程名称
bool started_; //标识线程的启动
bool joined_; //标识线程的是否在被等待
// 这样创建一个线程对象,绑定函数之后,线程会自动执行,无法控制,所以得换智能指针或容器
// std::thread thread_(任务,参数);
std::shared_ptr<std::thread> thread_;
pid_t tid_; // 线程 id
ThreadFunc func_; // 存储线程函数
std::string name_; // 线程名称
static std::atomic<int> numCreadted_; // 线程数量计数
};