-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion03.cpp
More file actions
70 lines (55 loc) · 2.18 KB
/
Copy pathquestion03.cpp
File metadata and controls
70 lines (55 loc) · 2.18 KB
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
//Question 3 - pointers
// There is a memory leak in the code below, where is it?, what class/solution can you use to fix it while ensuring that the object will be deleted only once and only when it's not used by any consumer
// Task: Modify the code to address the issues above. Please explain the changes you made and how they solve the memory allocation/deletion issue
// Do not remove any function or change threads dispatching order - you can(and should) change the functions body/signature
#include <chrono>
#include <iostream>
#include <vector>
#include <thread>
#include <random>
struct Payload {
Payload(uint64_t id_) :
id(id_),
veryLargeVector(1000*1000)
{}
//After reviewing the code, I noticed there is no distructor for the Payload class, so I added one.
//add a distructor to delete the veryLargeVector - the memory leak.
~Payload()
{
if (veryLargeVector.size() > 0) {
veryLargeVector.clear();
}
}
uint64_t id;
std::vector<int> veryLargeVector;
};
void operation1(Payload* payload) {
std::cout << "Performing operation1 on payload " << payload->id << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5 + (std::rand() % (12 - 5 + 1)))); //Simulate some heavy work
std::cout << "Operation1 Performed" << std::endl;
}
void operation2(Payload* payload) {
std::cout << "Performing operation2 on payload " << payload->id << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(std::chrono::seconds(5 + (std::rand() % (12 - 5 + 1))))); //Simulate some heavy work
std::cout << "Operation2 Performed" << std::endl;
}
void dispacher_thread() {
Payload* payload = new Payload(1);
std::this_thread::sleep_for(std::chrono::seconds(2)); //Simulate some heavy work
std::thread wt1(&operation1, payload);
std::thread wt2(&operation2, payload);
//Waiting for wt1 & wt2 to finish is not allowed, dispacher_thread should exit after creating wt1 and wt2
wt1.detach();
wt2.detach();
//release memory by calling destructor.
payload->~Payload();
}
int main(int argc, char** argv)
{
std::cout << "Calling dispatcher thread" << std::endl;
std::thread t(&dispacher_thread);
t.join();
std::cout << "Press enter to exit" << std::endl;
getchar();
return 0;
}