C++線程與線程池

C++多線程技術與線程池

0: 獲取線程ID


#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>

std::uint32_t lwp_id()
{
#if defined(APPLE) || defined(__APPLE__) || defined (__apple__)
	return static_cast<std::uint32_t>(std::this_thread::get_id());
#else
	return static_cast<std::uint32_t>(syscall(SYS_gettid));
#endif
}

1: C++線程技術

C++11提供了對線程技術的支持,

#include <thread>
#include <future>
#include <vector>
#include <iostream>
#include <cmath>
using namespace std;

struct result {
	vector<double> x;
	double y;
};

void f1(promise<result> &res)
{
	vector<double> vec(2);
	vec[0] = 1.5;
	vec[1] = 2.2;
	res.set_value({ vec, 4.7 });
}

double f2(double x)
{
	return sin(x);
}

int main(int argc, char* argv[])
{
	promise<result> res1;
	packaged_task<double(double)> res2(f2);
	future<result> ft1 = res1.get_future();
	future<double> ft2 = res2.get_future();
	thread th1(f1, ref(res1));       // 線程參數均爲copy,ref代表引用,必須顯式給出
	thread th2(move(res2), 3.14/6);  // 爲了提高性能採用move

	ft1.wait();
	ft2.wait();

	result r1 = ft1.get();
	double r2 = ft2.get();

	th1.join();  // 這兩句對此例不必要,僅爲了邏輯自洽給出
	th2.join();

	cout << "result: x = (" << r1.x[0] << ", " << r1.x[1] << "), y = " << r1.y << endl;
	cout << "sin(pi/6) = " << r2 << endl;
	return 0;
}

2: 線程池

//threadpool.h

#pragma once
#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <vector>
#include <queue>
#include <thread>
#include <atomic>
#include <condition_variable>
#include <future>

namespace ThreadPool
{
#define MAX_THREAD_NUM 8

//線程池,可以提交變參函數或lambda表達式的匿名函數執行,可以獲取執行返回值
//支持類成員函數,支持類靜態成員函數或全局函數,Operator()函數等
class ThreadPool
{
	typedef std::function<void()> Task;
private:
	std::vector<std::thread> m_pool;     // 線程池
	std::queue<Task> m_tasks;    // 任務隊列
	std::mutex m_lock;    // 同步鎖
	std::condition_variable m_cv;   // 條件阻塞
	std::atomic<bool> m_isStoped;    // 是否關閉提交
	std::atomic<int> m_idleThreadNum;  //空閒線程數量
public:
	ThreadPool(int size = MAX_THREAD_NUM) : m_isStoped(false)
	{
		size = size > MAX_THREAD_NUM ? MAX_THREAD_NUM : size;
		m_idleThreadNum = size;
		for (int i = 0; i < size; i++)
		{
			//初始化線程數量
			m_pool.emplace_back(&ThreadPool::scheduler, this);
		}
	}

	~ThreadPool()
	{
		Close();
		while (!m_tasks.empty())
		{
			m_tasks.pop();
		}
		m_cv.notify_all();  // 喚醒所有線程執行
		for (std::thread& thread : m_pool)
		{
			if (thread.joinable())
			{
				thread.join();  // 等待任務結束,前提是線程一定會執行完
			}
		}
		m_pool.clear();
	}

	// 打開線程池,重啓任務提交
	void ReOpen()
	{
		if (m_isStoped) m_isStoped.store(false);
		m_cv.notify_all();
	}

	// 關閉線程池,停止提交新任務
	void Close()
	{
		if (!m_isStoped) m_isStoped.store(true);
	}

	// 判斷線程池是否被關閉
	bool IsClosed() const
	{
		return m_isStoped.load();
	}

	// 獲取當前任務隊列中的任務數
	int GetTaskSize()
	{
		return m_tasks.size();
	}

	// 獲取當前空閒線程數
	int IdleCount()
	{
		return m_idleThreadNum;
	}

	// 提交任務並執行
	// 調用方式爲 std::future<returnType> var = threadpool.Submit(...)
	// var.get() 會等待任務執行完,並獲取返回值
	// 其中 ... 可以直接用函數名+函數參數代替,例如 threadpool.Submit(f, 0, 1)
	// 但如果要調用類成員函數,則最好用如下方式
	// threadpool.Submit(std::bind(&Class::Func, &classInstance)) 或
	// threadpool.Submit(std::mem_fn(&Class::Func), &classInstance)
	template<class F, class... Args>
	auto Submit(F&& f, Args&&... args)->std::future<decltype(f(args...))>
	{
		if (m_isStoped.load())
		{
			throw std::runtime_error("ThreadPool is closed, can not submit task.");
		}

		using RetType = decltype(f(args...));  // typename std::result_of<F(Args...)>::type, 函數 f 的返回值類型
		std::shared_ptr<std::packaged_task<RetType()>> task = std::make_shared<std::packaged_task<RetType()>>(
		    std::bind(std::forward<F>(f), std::forward<Args>(args)...)
		);
		std::future<RetType> future = task->get_future();
		// 封裝任務並添加到隊列
		addTask([task]()
		{
			(*task)();
		});

		return future;
	}
private:
	// 消費者
	Task getTask()
	{
		std::unique_lock<std::mutex> lock(m_lock); // unique_lock 相比 lock_guard 的好處是:可以隨時 unlock() 和 lock()
		while (m_tasks.empty() && !m_isStoped)
		{
			m_cv.wait(lock);
		}  // wait 直到有 task
		if (m_isStoped)
		{
			return Task();
		}
		assert(!m_tasks.empty());
		Task task = std::move(m_tasks.front()); // 取一個 task
		m_tasks.pop();
		m_cv.notify_one();
		return task;
	}

	// 生產者
	void addTask(Task task)
	{
		std::lock_guard<std::mutex> lock{ m_lock }; //對當前塊的語句加鎖, lock_guard 是 mutex 的 stack 封裝類,構造的時候 lock(),析構的時候 unlock()
		m_tasks.push(task);
		m_cv.notify_one(); // 喚醒一個線程執行
	}

	// 工作線程主循環函數
	void scheduler()
	{
		while (!m_isStoped.load())
		{
			// 獲取一個待執行的 task
			Task task(getTask());
			if (task)
			{
				m_idleThreadNum--;
				task();
				m_idleThreadNum++;
			}
		}
	}
};
}
#endif

測試函數

#include "threadpool.h"
#include <iostream>

struct gfun
{
	int operator()(int n)
	{
		printf("%d  hello, gfun !  %d\n", n, std::this_thread::get_id());
		return 42;
	}
};
#if defined(APPLE) || defined(__APPLE__) || defined (__apple__)
#include <sstream>
#endif
class Test
{
public:
	int GetThreadId(std::string a, double b)
	{
		std::this_thread::sleep_for(std::chrono::milliseconds(10000));
		std::thread::id i = std::this_thread::get_id();
		std::cout << "In Test, thread id: " << i << std::endl;
		std::cout << "a: " << a.c_str() << ", b = " << b << std::endl;

#if defined(APPLE) || defined(__APPLE__) || defined (__apple__) //for apple
		std::stringstream ss;
		ss << std::this_thread::get_id();
		int id = std::stoi(ss.str());
		return id;
#else
		return i.hash();
#endif
	}
};

int main()
{
	ThreadPool::ThreadPool worker{ 4 };
	Test t;
	std::cout << "at the beginning: " << std::endl;
	std::cout << "idle threads: " << worker.IdleCount() << std::endl;
	std::cout << "tasks: " << worker.GetTaskSize() << std::endl;
	std::future<int> f1 = worker.Submit(std::bind(&Test::GetThreadId, &t, "123", 456.789));

	std::cout << "after submit 1 task: " << std::endl;
	std::cout << "idle threads: " << worker.IdleCount() << std::endl;
	std::cout << "tasks: " << worker.GetTaskSize() << std::endl;
	std::future<int> f2 = worker.Submit(std::mem_fn(&Test::GetThreadId), &t, "789", 123.456);

	std::cout << "after submit 2 task: " << std::endl;
	std::cout << "idle threads: " << worker.IdleCount() << std::endl;
	std::cout << "tasks: " << worker.GetTaskSize() << std::endl;
	std::future<int> f3 = worker.Submit(gfun{}, 0);

	std::cout << "f1 = " << f1.get() << ", f2 = " << f2.get() << ", f3 = " << f3.get() << std::endl;

	std::cout << "after all task: " << std::endl;
	std::cout << "idle threads: " << worker.IdleCount() << std::endl;
	std::cout << "tasks: " << worker.GetTaskSize() << std::endl;
	return 0;
}

參考資料

  1. c++11多線程與線程池
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章