From 0f96c2e80f5dabd151322abcb9d2d5a4d1cf6665 Mon Sep 17 00:00:00 2001 From: sneaxiy Date: Wed, 5 Dec 2018 17:07:12 +0800 Subject: [PATCH] fix thread-safety bug test=develop --- paddle/fluid/platform/device_context.cc | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/paddle/fluid/platform/device_context.cc b/paddle/fluid/platform/device_context.cc index 5444fe3175..146a205832 100644 --- a/paddle/fluid/platform/device_context.cc +++ b/paddle/fluid/platform/device_context.cc @@ -120,14 +120,25 @@ class EigenCudaStreamDevice : public Eigen::StreamInterface { } void* allocate(size_t num_bytes) const override { + if (UNLIKELY(num_bytes == 0)) { + return nullptr; + } auto buf = paddle::memory::Alloc(place_, num_bytes, memory::Allocator::kScratchpad); void* retv = buf->ptr(); - allocations_[buf->ptr()] = std::move(buf); + { + std::lock_guard lock(mtx_); + allocations_.emplace(retv, std::move(buf)); + } return retv; } - void deallocate(void* buffer) const override { allocations_.erase(buffer); } + void deallocate(void* buffer) const override { + if (LIKELY(buffer)) { + std::lock_guard lock(mtx_); + allocations_.erase(buffer); + } + } void* scratchpad() const override { if (scratch_ == NULL) { @@ -153,6 +164,7 @@ class EigenCudaStreamDevice : public Eigen::StreamInterface { const cudaDeviceProp* device_prop_; // not owned; mutable void* scratch_; mutable unsigned int* semaphore_; + mutable std::mutex mtx_; // to protect allocations_ mutable std::unordered_map allocations_; };