Commit 40df8d85 by Xinfu L

Homework-14

parents
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<chrono>
#include<cstdlib>
#include<string>
using namespace std;
mutex mtx;
condition_variable cv;
bool ready = false;
void worker_work(string s) {
cout << "Worker is working on " << s << ". -- ";
}
void print_id(int id, string s) {
unique_lock<mutex> lck(mtx);
while(!ready) cv.wait(lck);
this_thread::sleep_for(chrono::milliseconds(rand() %200));
worker_work(s);
cout << "thread " << id << '\n';
}
void go() {
unique_lock<mutex> lck(mtx);
ready = true;
cv.notify_all();
}
int main() {
thread threads[10]; // 10 workers
for(int i=0; i<10; i++) {
threads[i] = thread(print_id, i, "this step");
}
cout << "10 workers are ready to work." << endl;
go();
for(auto &th : threads) {
th.join();
}
cout << "This step is finished!" << endl;
return 0;
}
\ No newline at end of file
#include<iostream>
#include<future>
using namespace std;
template<typename T>
class my_promise {
public:
my_promise() {}
future<T> get_future() {
unique_lock<mutex> lck(mtx);
while(!ready) cv.wait(lck);
return move(fut);
}
void set_value(T &v) {
ready = true;
val = v;
}
private:
future<T> fut;
T val;
mutex mtx;
condition_variable cv;
bool ready = false;
};
// this implementation of std::promise is partially created.
int main() {
return 0;
}
\ No newline at end of file
#include<iostream>
#include<future>
using namespace std;
int addNums(int a, int b) {
return a+b;
}
template<typename F, typename ...Args>
class my_packaged_task {};
template<typename F, typename ...Args>
class my_packaged_task<F(Args...)> {
public:
my_packaged_task(decay_t<F(*)(Args...)> f): func(f){}
// I discussed why using decay_t<F(*)(Args...)> here with Jiawei.
future<F> get_future() {
return move(p.get_future());
}
void operator()(Args ...args) {
p.set_value(func(args...));
}
private:
function<F(Args...)> func;
promise<F> p;
};
int main() {
my_packaged_task<int(int, int)> pt(addNums);
auto fut = pt.get_future();
thread t(move(pt), 1, 2);
t.join();
cout << fut.get() << endl;
return 0;
}
\ No newline at end of file
#include<iostream>
#include<future>
using namespace std;
int addNums(int a, int b) {
return a+b;
}
template<typename F, typename ...Args>
auto my_async(F &f, Args &&...args) {
packaged_task<F> pt(f);
auto fut = pt.get_future();
thread t(move(pt), args...);
t.join();
return fut;
}
int main() {
/*
auto fut = async(addNums, 1, 2);
cout << fut.get() << endl;
*/
auto fut = my_async(addNums, 2, 3);
cout << fut.get() << endl;
return 0;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment