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