版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013043408/article/details/83855565
C++11,包含头文件 thread.h,并使用命名空间std。
thread类提供的方法
方法 | 描述 |
---|---|
thread | 构造函数,在这里传入线程执行函数,和函数参数 |
get_id | 返回std::thread::id,这是一个类,可以间接得到unsigned型线程id |
joinable | 线程执行函数是否还没有退出 |
join | 阻塞,直到线程退出 |
detach | 分离线程,thread类放弃对线程执行函数的控制 |
swap | 交换线程 |
native_handle | 获取线程句柄 |
hardware_concurrency [static] | 检查线程并发特性 |
thread::id转unsigned型id
thread::id是一个类,可以F12查看它的源码。
参考代码
unsigned ThreadC11::getId()
{
stringstream buf;
m_thread->get_id()._To_text(buf);
unsigned id = 0;
buf >> id;
return id;
}
再封装thread
虽然C++11的thread已经很完美了,但要实现实用线程(执行函数无限循环并自然退出),还是有点欠缺。
也可下载完整测试代码
.h
#pragma once
typedef void(*proc_type)(void*);
namespace std {
class thread;
}
class ThreadC11
{
public:
ThreadC11(proc_type proc, void* param);
~ThreadC11();
friend void threadC11Pro(void* param);
//返回线程ID
unsigned getId();
private:
//结束
bool stop();
//禁止拷贝
ThreadC11(const ThreadC11 &) = delete;
//禁止赋值
ThreadC11& operator=(const ThreadC11 &) = delete;
private:
proc_type m_proc; //线程执行函数
void* m_param; //执行函数参数
bool m_alive; //线程是否活着
std::thread* m_thread; //线程对象
};
.cpp
添加了打印线程ID的测试代码,可适当剔除
#include "ThreadC11.h"
#include <thread>
#include <sstream>
#include <iostream>
#include <windows.h>
using namespace std;
static void threadC11Pro(void* param)
{
cout << "thread real id: " << GetCurrentThreadId() << endl;
ThreadC11* th = (ThreadC11*)param;
while (th->m_alive)
{
th->m_proc(th->m_param);
}
}
ThreadC11::ThreadC11(proc_type proc, void* param)
: m_proc(proc)
, m_param(param)
, m_alive(true)
{
m_thread = new thread(threadC11Pro, this);
}
ThreadC11::~ThreadC11()
{
stop();
delete m_thread;
}
unsigned ThreadC11::getId()
{
stringstream buf;
m_thread->get_id()._To_text(buf);
unsigned id;
buf >> id;
cout << "thread may id: " << id << endl;
return id;
}
bool ThreadC11::stop()
{
m_alive = false;
if (m_thread->joinable())
{
m_thread->join();
}
return true;
}