feat: add mutex and set a fixed number for ThreadPool
#36
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::chrono::system_clock::now().time_since_epoch()
:获取从 1970 年开始到现在经过的时间,算作时间段,但是由于是从 0 开始的,所以也可以算作是时间点。bad_alloc:说明无法分配内存。system_error:无法创建新线程。
线程池里用 thread 实现,即
std::launch::async 和 std::thread 是一样的,都是创建之后就马上开始运行子线程。但是这样并不能把 262144 * 3 个子线程全部执行完,当 i = 10830 的时候就报 system_error,无法创建新线程了;如果用 std::launch::deferred 惰性执行就没有问题,可以成功执行并且退出;如果不特意指定异步的启动方式,它可能是两者其中之一,但是也只能运行 24w 左右。
解决方案就是增加检测 vector 长度的代码,如果 vector 过长,则先等待 vector 中的线程或者协程执行完,才能增加新的线程。通过手动限制线程池的大小,避免了这个问题。