Skip to content

Commit 4896058

Browse files
committed
Stabilize multi-producer state buffer preallocation
1 parent a8d0dc1 commit 4896058

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

envpool/core/state_buffer_queue.h

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include <algorithm>
2121
#include <cstdint>
2222
#include <list>
23+
#include <mutex>
2324
#include <memory>
2425
#include <thread>
2526
#include <utility>
@@ -43,6 +44,7 @@ class StateBufferQueue {
4344

4445
// Create stock statebuffers in a background thread
4546
CircularBuffer<std::unique_ptr<StateBuffer>> stock_buffer_;
47+
std::mutex stock_buffer_put_mu_;
4648
std::vector<std::thread> create_buffer_thread_;
4749
std::atomic<bool> quit_;
4850

@@ -87,8 +89,12 @@ class StateBufferQueue {
8789
for (std::size_t i = 0; i < create_buffer_thread_num; ++i) {
8890
create_buffer_thread_.emplace_back([&]() {
8991
while (true) {
90-
stock_buffer_.Put(std::make_unique<StateBuffer>(
91-
batch_, max_num_players_, specs_, is_player_state_));
92+
auto buffer = std::make_unique<StateBuffer>(batch_, max_num_players_,
93+
specs_, is_player_state_);
94+
{
95+
std::lock_guard<std::mutex> lock(stock_buffer_put_mu_);
96+
stock_buffer_.Put(std::move(buffer));
97+
}
9298
if (quit_) {
9399
break;
94100
}

0 commit comments

Comments
 (0)