-
Notifications
You must be signed in to change notification settings - Fork 2
/
STL_task.cpp
111 lines (95 loc) · 1.86 KB
/
STL_task.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*This piece of code tests out std::packaged_task in the Standard Library. Use the flag -pthread to link the POSIX thread library.*/
#include <functional>
#include <thread>
#include <iostream>
#include <memory>
struct Foo
{
int num;
Foo(int n) : num(n) {}
int fact()
{
if (num <= 1)
return 1;
else
{
int p = 1;
for (int i = 1; i <= num; i++)
p *= i;
return p;
}
}
void printFib()
{
int current = 1, next = 1, fib = 0;
if(num < 1)
{
std::cout << "Invalid input" << std::endl;
return;
}
if (num <= 2)
{
std::cout << "Fibonacci term: " << num << std::endl;
return;
}
for(int i = 3; i <= num; i++)
{
fib = current + next;
current = next;
next = fib;
}
std::cout << "Fibonacci term: " << fib << std::endl;
}
};
struct ITask
{
enum struct TaskState
{
Uninitialized,
Waiting,
Running,
Paused,
Finished
};
};
template
<typename T>
struct Task : public ITask
{
TaskState state;
std::function<T()> job;
Task(std::function<T()> &job_) : state(TaskState::Uninitialized), job(std::move(job_)) {}
T run()
{
state = TaskState::Running;
std::cout << "Starting execution..." << std::endl;
return job();
}
};
int main()
{
Foo f1(15);
std::function<int()> tempTask(std::bind(&Foo::fact, &f1));
Task<int> task(std::ref(tempTask));
std::thread t1([&] ()
{
int result = task.run();
std::cout << result << std::endl;
});
t1.join();
Foo f2(20);
std::function<void()> tempTask2(std::bind(&Foo::printFib, &f2));
Task<void> task2(std::ref(tempTask2));
std::thread t2([&] () { task2.run(); });
t2.join();
Foo f3(12);
std::function<int()> tempTask3(std::bind(&Foo::fact, &f3));
ITask *tPtr = new Task<int>(std::ref(tempTask3));
std::thread t3([&] ()
{
Task<int> *taskPtr = (Task<int>*)tPtr;
int result = taskPtr->run();
std::cout << result << std::endl;
});
t3.join();
}