1. 程式人生 > >C++多執行緒之std::thread

C++多執行緒之std::thread

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;
}