[C++11]多线程编程之future用法(逐步完善)

#include <thread>
#include <mutex>
#include <future>
#include <condition_variable>
#include <iostream>
#include <windows.h>

using namespace std;

class A {
public:
	std::mutex begin_lock;
	std::condition_variable cv;
	std::mutex my_lock;
	bool begin_flag;
	int num;
	A() {
		num = 10000;
		begin_flag = true;
	}
	~A() {}

};

int transmit(A* a, int thread_num) {
	std::unique_lock <std::mutex> _5412_lock(a->begin_lock);
	cout << "Thread " << std :: this_thread :: get_id() << " working" << endl;
	a->cv.wait(_5412_lock, [&a]() {
		return a->begin_flag == true;
	});
	a->my_lock.lock();
	a->num--;
	a->my_lock.unlock();
	return thread_num + 1;
}

int main() {
	A a;
	cout << "Thread " << std :: this_thread::get_id() << " working" << endl;
	std :: packaged_task <int(A*, int)> pac(transmit);
	//std :: future <int> *fu1 = new std :: future <int>;
	std::future <int> fu1 = pac.get_future();
	thread my_thread_obj(move(pac), &a, 10);
	my_thread_obj.join();
	//std::future <int> fu1 = std::async(*pac, &a, 0);
	std::this_thread::sleep_for(std::chrono::seconds(5));
	a.begin_flag = true;
	a.cv.notify_all();
	fu1.wait();
    cout << "Result = " << fu1.get() << endl;
	cout << "num = " << a.num << endl;
	system("pause");
    return 0;
}

使用指针的写法,适用于使用容器和循环大量创建线程,但是作用域又想要大于循环体的时候:

#include <thread>
#include <mutex>
#include <future>
#include <condition_variable>
#include <iostream>
#include <windows.h>

using namespace std;

class A {
public:
	std::mutex begin_lock;
	std::condition_variable cv;
	std::mutex my_lock;
	bool begin_flag;
	int num;
	A() {
		num = 10000;
		begin_flag = true;
	}
	~A() {}

};

int transmit(A* a, int thread_num) {
	std::unique_lock <std::mutex> _5412_lock(a->begin_lock);
	cout << "Thread " << std :: this_thread :: get_id() << " working" << endl;
	a->cv.wait(_5412_lock, [&a]() {
		return a->begin_flag == true;
	});
	a->my_lock.lock();
	a->num--;
	a->my_lock.unlock();
	return thread_num + 1;
}

int main() {
	A a;
	cout << "Thread " << std :: this_thread::get_id() << " working" << endl;
	std :: packaged_task <int(A*, int)> *pac = new std :: packaged_task <int(A*, int)> (transmit);
	std::future <int>* fu1 = new std::future<int>;
	(*fu1) = (*pac).get_future();
	thread *my_thread_obj = new thread(move(*pac), &a, 10);
	(*my_thread_obj).join();
	//std::future <int> fu1 = std::async(*pac, &a, 0);
	std::this_thread::sleep_for(std::chrono::seconds(5));
	a.begin_flag = true;
	a.cv.notify_all();
	(*fu1).wait();
    cout << "Result = " << (*fu1).get() << endl;
	cout << "num = " << a.num << endl;
	system("pause");
	delete pac;
	delete fu1;
	delete p_my_thread_obj;
    return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值