Skip to content

Commit 4ae935e

Browse files
committed
refine the lock in scope
1 parent 944bdee commit 4ae935e

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

paddle/fluid/framework/scope.cc

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,10 @@ Scope& Scope::NewScope() const {
4949
}
5050

5151
Variable* Scope::Var(const std::string& name) {
52-
auto* v = FindVarLocally(name);
53-
if (v != nullptr) return v;
5452
// acquire the lock when new var under this scope
5553
std::unique_lock<std::mutex> lock(mutex_);
54+
auto* v = FindVarLocally(name);
55+
if (v != nullptr) return v;
5656
v = new Variable();
5757
vars_[name] = v;
5858
VLOG(3) << "Create variable " << name;
@@ -69,11 +69,17 @@ Variable* Scope::Var(std::string* name) {
6969
}
7070

7171
Variable* Scope::FindVar(const std::string& name) const {
72+
// acquire the lock when find var
73+
std::unique_lock<std::mutex> lock(mutex_);
74+
return FindVarInternal(name);
75+
}
76+
77+
Variable* Scope::FindVarInternal(const std::string& name) const {
7278
auto var = FindVarLocally(name);
7379
if (var != nullptr) {
7480
return var;
7581
}
76-
return (parent_ == nullptr) ? nullptr : parent_->FindVar(name);
82+
return (parent_ == nullptr) ? nullptr : parent_->FindVarInternal(name);
7783
}
7884

7985
const Scope* Scope::FindScope(const Variable* var) const {
@@ -144,8 +150,6 @@ std::string Scope::Rename(const std::string& origin_name) const {
144150
}
145151

146152
Variable* Scope::FindVarLocally(const std::string& name) const {
147-
// acquire the lock when find locally
148-
std::unique_lock<std::mutex> lock(mutex_);
149153
auto it = vars_.find(name);
150154
if (it != vars_.end()) return it->second;
151155
return nullptr;

paddle/fluid/framework/scope.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,16 @@ class Scope {
7878
// Rename variable to a new name and return the new name
7979
std::string Rename(const std::string& origin_name) const;
8080

81-
Variable* FindVarLocally(const std::string& name) const;
82-
8381
private:
8482
// Call Scope::NewScope for a sub-scope.
8583
explicit Scope(Scope const* parent) : parent_(parent) {}
8684

85+
// Called by FindVar recursively
86+
Variable* FindVarInternal(const std::string& name) const;
87+
88+
// Called by FindVarInternal and Var
89+
Variable* FindVarLocally(const std::string& name) const;
90+
8791
mutable std::unordered_map<std::string, Variable*> vars_;
8892
mutable std::list<Scope*> kids_;
8993
Scope const* parent_{nullptr};

0 commit comments

Comments
 (0)