Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
核心改进说明:
引入了 std::shared_mutex 对全局数据 users 和 has_login 进行保护。
读写分离优化:在 do_queryuser 函数中使用了 std::shared_lock,允许多个线程同时进行查询操作,极大提高了读密集型场景的并发性能。
在 do_register 和 do_login 中使用了 std::unique_lock,确保在修改用户信息或更新登录状态时,数据的一致性和完整性。
废弃了不精确且易受系统时间调整影响的 C 语言 time(NULL)。
将 has_login 的值类型改为 std::chrono::steady_clock::time_point。
使用 std::chrono::steady_clock 计算两次登录的时间差,保证了计时的单调递增和高精度,符合现代 C++ 后端开发的标准实践。
重构了 ThreadPool 类。原代码中直接创建 std::thread 会导致由于对象生命周期结束而触发 std::terminate。
改用 std::async(std::launch::async, ...) 启动异步任务。
通过 std::vector<std::future> 收集任务凭证,并在 main 函数末尾调用 wait_all()(循环调用 .wait()),优雅地实现了“后台执行 + 统一回收”的逻辑。
测试结果:
在并行度为 4096 的高并发压力测试下,程序运行平稳。
输出结果显示,注册、登录及查询逻辑均能正确互斥或并行,未发现由于竞态条件导致的内存错误或逻辑异常。