C++多線程和QT多線程(一)

因爲工程需要處理大量的圖片,這段時間看了一下C++多線程的相關內容,並參照網上寫的多線程類,運用到自己的工程中。

一 多線程

https://blog.csdn.net/invincibleFF/article/details/80048868  這篇文章介紹的很詳細。關於多線程是什麼。在計算時間相對較長,計算量相對較大的並行計算時,使用多線程可以極大的提高運算速度。

二 多線程的使用

我在網上找的一個多線程類ThreadPool.h,代碼如下(如果該代碼原作者看到,請留言,由於時間很長,是在找不到原作者了。):

#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>

class ThreadPool {
public:
	ThreadPool(size_t);
	template<class F, class... Args>
	auto enqueue(F&& f, Args&&... args)
		->std::future<typename std::result_of<F(Args...)>::type>;
	~ThreadPool();
private:
	// need to keep track of threads so we can join them
	std::vector< std::thread > workers;
	// the task queue
	std::queue< std::function<void()> > tasks;

	// synchronization
	std::mutex queue_mutex;
	std::condition_variable condition;
	bool stop;
};

// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
	for (size_t i = 0; i < threads; ++i)
		workers.emplace_back(
		[this]
	{
		for (;;)
		{
			std::function<void()> task;

			{
				std::unique_lock<std::mutex> lock(this->queue_mutex);
				this->condition.wait(lock,
					[this]{ return this->stop || !this->tasks.empty(); });
				if (this->stop && this->tasks.empty())
					return;
				task = std::move(this->tasks.front());
				this->tasks.pop();
			}

			task();
		}
	}
	);
}

// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
	using return_type = typename std::result_of<F(Args...)>::type;

	auto task = std::make_shared< std::packaged_task<return_type()> >(
		std::bind(std::forward<F>(f), std::forward<Args>(args)...)
		);

	std::future<return_type> res = task->get_future();
	{
		std::unique_lock<std::mutex> lock(queue_mutex);

		// don't allow enqueueing after stopping the pool
		if (stop)
			throw std::runtime_error("enqueue on stopped ThreadPool");

		tasks.emplace([task](){ (*task)(); });
	}
	condition.notify_one();
	return res;
}

// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
	{
		std::unique_lock<std::mutex> lock(queue_mutex);
		stop = true;
	}
	condition.notify_all();
	for (std::thread &worker : workers)
		worker.join();
}

#endif

直接添加這個類。

應用:

double terr(int i)
{
	double area_i = i* i * 3.14;
	area_i = area_i*area_i;
	return area_i;
}

void main()
{
	std::mutex mutex_tmp;
	float startTime0, endTime0;
	//定義線程數
	int tread_num = 10;
	ThreadPool pool(tread_num);
	///任務隊列  放任務函數
	std::vector< std::future<double> > results;
	for (int i = 0; i != 1000000; i++)
	{
		results.emplace_back(pool.enqueue(bind(terr, i)));
	}
	//計時
	startTime0 = omp_get_wtime();
	vector<std::future<double>>::iterator result;

	for (result = results.begin(); result != results.end(); result++)
	{
		mutex_tmp.lock();
		result->get();
		mutex_tmp.unlock();
	}
	endTime0 = omp_get_wtime();
	cout << tread_num << "個線程處理時間爲 : " << endTime0 - startTime0 << endl;
	system("pause");
	return;
}

results.emplace_back(pool.enqueue(bind(terr, i)));將任務函數放到隊列中。並使用result->get();得到最後的計算結果。

 

 

以上是C++實現多線程計算的一種方式。還有使用openmp的方式:https://blog.csdn.net/zcgyq/article/details/83088324可以參考這篇博文,關於openmp的用法更爲簡單。

 

下面介紹QT多線程用法。

 

 

 

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