add teller threading
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
OUT_DIR := build
|
||||
OUT_BIN := $(OUT_DIR)/banker
|
||||
|
||||
$(OUT_BIN): banker.c
|
||||
$(OUT_BIN): banker.cpp
|
||||
mkdir -p $(OUT_DIR)
|
||||
gcc -pthread banker.c -o $(OUT_BIN)
|
||||
g++ -pthread banker.cpp -o $(OUT_BIN)
|
||||
|
||||
.PHONY: run
|
||||
run: $(OUT_BIN)
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <pthread.h>
|
||||
|
||||
int main() {
|
||||
return 0;
|
||||
}
|
||||
73
lab1/banker.cpp
Normal file
73
lab1/banker.cpp
Normal file
@@ -0,0 +1,73 @@
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <deque>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <semaphore>
|
||||
|
||||
#define TELLER_NUM 5
|
||||
#define TIME_GRAN_MSEC 200
|
||||
|
||||
std::atomic<bool> bank_open = false;
|
||||
std::mutex custom_q_mtx;
|
||||
std::counting_semaphore custom_num_sem;
|
||||
|
||||
std::deque<Customer> customer_q;
|
||||
|
||||
|
||||
struct CustomerInfo {
|
||||
unsigned int id;
|
||||
unsigned int arrival_time;
|
||||
unsigned int service_time;
|
||||
};
|
||||
|
||||
struct Customer {
|
||||
unsigned int id;
|
||||
unsigned int service_time;
|
||||
};
|
||||
|
||||
void teller_thread(int id, std::chrono::time_point<std::chrono::steady_clock> start_tick) {
|
||||
std::cout << "Teller id " << id << " started\n";
|
||||
std::chrono::time_point curr_tick = start_tick;
|
||||
bool is_serving = false;
|
||||
std::chrono::time_point<std::chrono::steady_clock> start_serving_time;
|
||||
struct Customer curr_customer;
|
||||
while (bank_open) {
|
||||
if (is_serving && ((curr_tick - start_serving_time) / TIME_GRAN_MSEC) >= curr_customer.service_time) {
|
||||
|
||||
}
|
||||
std::cout << "Teller id " << id << " waiting request\n";
|
||||
|
||||
|
||||
curr_tick += std::chrono::milliseconds(TIME_GRAN_MSEC);
|
||||
std::this_thread::sleep_until(curr_tick);
|
||||
}
|
||||
std::cout << "Teller id " << id << " closing\n";
|
||||
}
|
||||
|
||||
int main() {
|
||||
bank_open = true;
|
||||
|
||||
std::vector<std::thread> tellers;
|
||||
for (int i = 0; i < TELLER_NUM; ++i) {
|
||||
try {
|
||||
tellers.emplace_back(teller_thread, i);
|
||||
} catch (const std::system_error& e) {
|
||||
std::cerr << "Failed to create thread, i = " << i << ": " << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5 * TIME_GRAN_MSEC));
|
||||
std::cout << "Closing all child\n";
|
||||
bank_open = false;
|
||||
|
||||
for (auto& t : tellers) {
|
||||
if (t.joinable()) {
|
||||
t.join();
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user