C++11 多线程

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/csdn1126274345/article/details/85938332
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <chrono>

using namespace std;

std::mutex mt;
std::condition_variable cond;
bool flag = false; //设置全局标志位
template<typename T>
class Add{
public:
	T operator()(T x ,T y){//仿函数
		cout << "enter functor x + y = " << x + y << endl;
		cout << "std::this_thread::get_pid() = " << std::this_thread::get_id() << endl;
		return x + y;
	}
};

class Tax {
public:
	Tax(float r, float b):_rate(r),_base(b){}
#if 0	
	float operator()(float money)//带状态的仿函数
	{
		//std::lock_guard<std::mutex> lk(mt);
		/*
		threadtest.cpp:74:15: error: no matching function for call to 'std::condition_variable::wait(std::lock_guard<std::mutex>&)'
        cond.wait(lk);
               ^
        In file included from threadtest.cpp:4:0:
        D:/mingw64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/condition_variable:92:5: note: candidate: void std::condition_variable::wait(std                                                                   ::unique_lock<std::mutex>&)
        wait(unique_lock<mutex>& __lock) noexcept;
        ^~~~
		*/
		std::unique_lock<std::mutex> lk(mt);//更加灵活,功能更加强大,付出更多的时间、性能成本
		cout << "Enter Tax functor!" << endl;
		cout << (money-_base)*_rate << endl;
		return (money-_base)*_rate;
		cond.notify_one();
	}
#else
	void operator()(float money, float &rest)
	{
		//std::lock_guard<std::mutex> lk(mt);
		std::unique_lock<std::mutex> lk(mt);
		cout << "Enter Tax functor!" << endl;
		cout << "std::this_thread::get_pid() = " << std::this_thread::get_id() << endl;
		cout << (money-_base)*_rate << endl;
		rest = (money-_base)*_rate;
		flag = true;
		cond.notify_one();
	}
#endif	
private:
	float _rate;
	float _base;
};

void func(int &x, string &str)
{
	cout << "Enter func!" << endl;
	cout << "func thread'id is " << std::this_thread::get_id() << endl;
	x = x*1000;
	cout << "str = " << str << endl;
	str = "str has been changed!\n";
	//return x;
}
int main(int argc, char *argv[])
{
	cout << "__cplusplus = " << __cplusplus <<endl;
	cout << "============Test thread with lambda!" << endl;
	string s = "lambda string !";
	int x = 234;
	string str1 = "adsads";
	thread tl([&s](int x, string str){
		cout << "thread-lambda run!" << endl;
		cout << "std::this_thread::get_pid() = " << std::this_thread::get_id() << endl;
		cout << s << endl;
		cout << x << endl;
		cout << str << endl;
		//}, s, 199, "adbc"); //ERROR
		//}, 199, "adbc");//OK
		}, x, str1);//OK
	
	cout << "=============Test thread with functor!" << endl;
	Add<int> add;
	thread tf(add, 1, 2);
	//thread tf(Add<int>(1, 2), 1, 2);//compile error!
	cout << "=============Test thread with functor-status!" << endl;
	float rest;
	Tax high(0.3, 40000);
	//thread tfs(high, 50000);
	//thread tfs(high, 50000, rest);
	thread tfs(high, 50000, std::ref(rest));//thread传引用需要用std::ref
	{	
		//std::lock_guard<std::mutex> lk(mt);
		std::unique_lock<std::mutex> lk(mt);
#if 0
			cond.wait(lk);//此方式多次运行会出现卡主
			cout << "The money of Tax_after : " << rest << endl;
#else
		while (!flag) {
			cond.wait(lk);
			cout << "The money of Tax_after : " << rest << endl;
		}
#endif
	}
	cout << "after cond.wait!" << endl;
	cout << "main thread id = " << std::this_thread::get_id() << endl;
	
	cout << "==============Test parameter passed by reference!" << endl;
	int xx = 4;
	string str = "abc";
	//std::thread tfr(func, xx, str);//compile error
	std::thread tfr(func, std::ref(xx), std::ref(str));//ok
	//std::thread tfr(func, std::move(xx), std::move(str));//compile error
	std::thread t2 = std::move(tfr);
	cout << "tfr id = " << tfr.get_id() << endl;//tfr id = thread::id of a non-executing thread
	cout << "t2 id = " << t2.get_id() << endl;
	std::this_thread::sleep_for(std::chrono::seconds(1));// 主线程睡眠1s,让子线程改变值
	cout << "str after thread = " << str << endl;
	
	cout << "硬件上能并发的线程数目 = " << std::thread::hardware_concurrency() << endl;
	t2.join();
	tfs.join();
	tf.join();
	tl.join();
	return 0;
}

 

#include <iostream>
#include <thread>
#include <vector>
#include <future>

using namespace std;

template<class T>
void spend_time(T&& func)
{
	using namespace std::chrono;
	auto start = system_clock::now();
	func();
	duration<double> diff = system_clock::now() - start;
	cout << "Spend time : " << diff.count() << " seconds" << endl;
}

void sum(long start, long end, long long &ret)
{   
    ret = 0;
	long long sum = 0;
	for (long i = start; i < end; i++)
		sum += i;
	    //ret += i;//不直接使用引用变量,提高效率
	ret = sum;
	cout << "function sum = " << ret << endl;	
}
long long sum1(long start, long end)
{
	long long s = 0;
	for (long i = start; i < end; i++)
		s += i;
	return s;
}

const long s = 200000000;

int main(int argc, char *argv[])
{
#if 0
	spend_time([](){
		long long ret1,ret2;
		std::thread th1(sum, 0, s/2, std::ref(ret1));
		std::thread th2(sum, s/2, s, std::ref(ret2));
		th1.join();
		th2.join();
		cout << "Muti Threads total = " << ret1 + ret2 << endl;
	});
	
	spend_time([](){
		long long ret3;
		sum(0, s, ret3);
		cout << "Not muti threads total = " << ret3 << endl;
	});
#else
	spend_time([](){
		const long k = 4;
		vector<future<long long>> vf;
		vf.reserve(k);
		for (long i = 0; i < k; i++){
			vf.push_back(async(sum1, i == 0 ? 0 : (s / k) * i, (s / k) * (i + 1)));
			/*模板函数 async 异步地运行函数 f (潜在地在可能是线程池一部分的分离线程中),并返回最终将保有该函数调用结果的 std::future 。*/
		}
		
		long long total = 0;
		for (int i = 0; i < k; i++)
			total += vf[i].get();//返回结果 
		cout << "Total = " << total << endl;
	});
#endif

	return 0;
}

 

展开阅读全文

没有更多推荐了,返回首页