Repository navigation
Expand file tree
/
Copy pathmedium.cpp
More file actions
221 lines (199 loc) · 7.42 KB
/
Copy pathmedium.cpp
File metadata and controls
221 lines (199 loc) · 7.42 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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// medium.cpp
// A medium-sized C++ example: a simple concurrent Task Manager
// Features: Task class, TaskManager with thread pool, save/load, interactive CLI
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <mutex>
#include <queue>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
using namespace std::chrono_literals;
struct Task {
int id;
std::string name;
int duration_seconds; // simulated work duration
Task() = default;
Task(int i, std::string n, int d) : id(i), name(std::move(n)), duration_seconds(d) {}
std::string serialize() const {
// simple pipe-separated format: id|name|duration
std::ostringstream ss;
ss << id << '|' << name << '|' << duration_seconds;
return ss.str();
}
static Task deserialize(const std::string& line) {
std::istringstream ss(line);
std::string part;
Task t;
if (std::getline(ss, part, '|')) t.id = std::stoi(part);
if (std::getline(ss, part, '|')) t.name = part;
if (std::getline(ss, part, '|')) t.duration_seconds = std::stoi(part);
return t;
}
};
class TaskManager {
public:
TaskManager() : next_id_(1) {}
int add_task(const std::string& name, int duration_seconds) {
std::lock_guard<std::mutex> lk(m_);
int id = next_id_++;
tasks_.push_back(std::make_shared<Task>(id, name, duration_seconds));
return id;
}
bool remove_task(int id) {
std::lock_guard<std::mutex> lk(m_);
auto it = std::remove_if(tasks_.begin(), tasks_.end(), [id](const auto& t){ return t->id == id; });
if (it == tasks_.end()) return false;
tasks_.erase(it, tasks_.end());
return true;
}
std::vector<std::shared_ptr<Task>> list_tasks() const {
std::lock_guard<std::mutex> lk(m_);
return tasks_;
}
bool save_to_file(const std::string& filename) const {
std::lock_guard<std::mutex> lk(m_);
std::ofstream ofs(filename, std::ios::trunc);
if (!ofs) return false;
for (const auto& t : tasks_) ofs << t->serialize() << '\n';
return true;
}
bool load_from_file(const std::string& filename) {
std::lock_guard<std::mutex> lk(m_);
std::ifstream ifs(filename);
if (!ifs) return false;
tasks_.clear();
std::string line;
int highest = 0;
while (std::getline(ifs, line)) {
if (line.empty()) continue;
Task t = Task::deserialize(line);
highest = std::max(highest, t.id);
tasks_.push_back(std::make_shared<Task>(t));
}
next_id_ = highest + 1;
return true;
}
// Run all tasks using a simple worker thread pool. Each task sleeps to simulate work.
void run_all(int worker_count = 2) {
std::vector<std::shared_ptr<Task>> snapshot;
{
std::lock_guard<std::mutex> lk(m_);
snapshot = tasks_;
}
if (snapshot.empty()) {
std::cout << "No tasks to run.\n";
return;
}
std::queue<std::shared_ptr<Task>> q;
for (auto& t : snapshot) q.push(t);
std::mutex q_m;
std::condition_variable cv;
std::atomic<int> active_workers{0};
std::atomic<int> completed{0};
auto worker = [&](int worker_id){
while (true) {
std::shared_ptr<Task> tsk;
{
std::unique_lock<std::mutex> lk(q_m);
if (q.empty()) break;
tsk = q.front(); q.pop();
active_workers.fetch_add(1);
}
std::cout << "[Worker " << worker_id << "] Starting task " << tsk->id << ": " << tsk->name << " (" << tsk->duration_seconds << "s)\n";
for (int s = 0; s < tsk->duration_seconds; ++s) {
std::this_thread::sleep_for(1s);
std::cout << "[Task " << tsk->id << "] progress: " << (s+1) << "s / " << tsk->duration_seconds << "s\n";
}
std::cout << "[Worker " << worker_id << "] Finished task " << tsk->id << "\n";
active_workers.fetch_sub(1);
completed.fetch_add(1);
}
};
std::vector<std::thread> threads;
for (int i = 0; i < worker_count; ++i) threads.emplace_back(worker, i+1);
for (auto& th : threads) if (th.joinable()) th.join();
std::cout << "All tasks completed: " << completed.load() << " tasks." << std::endl;
}
private:
mutable std::mutex m_;
std::vector<std::shared_ptr<Task>> tasks_;
int next_id_;
};
static void print_menu() {
std::cout << "\n=== Task Manager ===\n";
std::cout << "1) Add task\n";
std::cout << "2) List tasks\n";
std::cout << "3) Remove task\n";
std::cout << "4) Run all tasks (concurrent)\n";
std::cout << "5) Save tasks to file\n";
std::cout << "6) Load tasks from file\n";
std::cout << "7) Exit\n";
std::cout << "Choose an option: ";
}
int main() {
TaskManager mgr;
// Add some demo tasks
mgr.add_task("Compile project", 2);
mgr.add_task("Run unit tests", 3);
mgr.add_task("Generate docs", 1);
bool running = true;
while (running) {
print_menu();
int opt = 0;
if (!(std::cin >> opt)) break;
switch (opt) {
case 1: {
std::string name; int dur;
std::cout << "Task name: ";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin, name);
std::cout << "Duration seconds: ";
if (!(std::cin >> dur)) { std::cin.clear(); std::cin.ignore(); dur = 1; }
int id = mgr.add_task(name, dur);
std::cout << "Added task id " << id << "\n";
break;
}
case 2: {
auto tasks = mgr.list_tasks();
std::cout << "Current tasks:\n";
for (const auto& t : tasks) {
std::cout << " [" << t->id << "] " << t->name << " (" << t->duration_seconds << "s)\n";
}
break;
}
case 3: {
int id; std::cout << "Remove task id: "; if (!(std::cin >> id)) { std::cin.clear(); std::cin.ignore(); break; }
if (mgr.remove_task(id)) std::cout << "Removed.\n"; else std::cout << "Not found.\n";
break;
}
case 4: {
int workers; std::cout << "Worker threads to use (1-8): "; if (!(std::cin >> workers)) { workers = 2; }
workers = std::clamp(workers, 1, 8);
mgr.run_all(workers);
break;
}
case 5: {
std::string fn; std::cout << "Filename: "; std::cin >> fn;
if (mgr.save_to_file(fn)) std::cout << "Saved.\n"; else std::cout << "Save failed.\n";
break;
}
case 6: {
std::string fn; std::cout << "Filename: "; std::cin >> fn;
if (mgr.load_from_file(fn)) std::cout << "Loaded.\n"; else std::cout << "Load failed.\n";
break;
}
case 7: running = false; break;
default: std::cout << "Invalid option.\n"; break;
}
}
std::cout << "Bye.\n";
return 0;
}