Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 29 additions & 7 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
#include <string>
#include <thread>
#include <map>
#include <shared_mutex>
#include <vector>
#include <future>


struct User {
Expand All @@ -14,13 +17,16 @@ struct User {
std::string phone;
};

std::shared_mutex users_mtx;
std::map<std::string, User> users;
std::map<std::string, long> has_login; // 换成 std::chrono::seconds 之类的
std::mutex has_login_mtx;
std::map<std::string, std::chrono::time_point<std::chrono::steady_clock>> has_login; // 换成 std::chrono::seconds 之类的

// 作业要求1:把这些函数变成多线程安全的
// 提示:能正确利用 shared_mutex 加分,用 lock_guard 系列加分
std::string do_register(std::string username, std::string password, std::string school, std::string phone) {
User user = {password, school, phone};
std::lock_guard<std::shared_mutex> lock(users_mtx);
if (users.emplace(username, user).second)
return "注册成功";
else
Expand All @@ -29,13 +35,19 @@ std::string do_register(std::string username, std::string password, std::string

std::string do_login(std::string username, std::string password) {
// 作业要求2:把这个登录计时器改成基于 chrono 的
long now = time(NULL); // C 语言当前时间
if (has_login.find(username) != has_login.end()) {
int sec = now - has_login.at(username); // C 语言算时间差
return std::to_string(sec) + "秒内登录过";
auto now = std::chrono::steady_clock::now();

{
std::lock_guard<std::mutex> lock(has_login_mtx);
if (has_login.find(username) != has_login.end()) {
auto dt = now - has_login.at(username);
int64_t sec = std::chrono::duration_cast<std::chrono::seconds>(dt).count();
return std::to_string(sec) + "秒内登录过";
}
has_login[username] = now;
}
has_login[username] = now;

std::shared_lock<std::shared_mutex> lock(users_mtx);
if (users.find(username) == users.end())
return "用户名错误";
if (users.at(username).password != password)
Expand All @@ -44,6 +56,7 @@ std::string do_login(std::string username, std::string password) {
}

std::string do_queryuser(std::string username) {
std::shared_lock<std::shared_mutex> lock(users_mtx);
auto &user = users.at(username);
std::stringstream ss;
ss << "用户名: " << username << std::endl;
Expand All @@ -54,11 +67,20 @@ std::string do_queryuser(std::string username) {


struct ThreadPool {

void create(std::function<void()> start) {
// 作业要求3:如何让这个线程保持在后台执行不要退出?
// 提示:改成 async 和 future 且用法正确也可以加分
std::thread thr(start);
_futures.push_back(std::async(start));
}

~ThreadPool() {
for (auto &fut: futures_) {
fut.wait();
}
}
private:
std::vector<std::future<void>> _futures;
};

ThreadPool tpool;
Expand Down