TM: Add mutex to access LongLivedObjectCollection - making it thread safe
Summary: There are cases where the CallbackWrapper instances were added from different thread, potentially crashing the inner std::unordered_set<> we're using to keep the wrappers alive for extended time. To avoid it, let's just use std::mutex. Reviewed By: shergin Differential Revision: D17631233 fbshipit-source-id: e8f98004e45a68be31f8f0cda118fb67dcb06d45
This commit is contained in:
Родитель
de17cdecd8
Коммит
1452954c4c
|
@ -18,11 +18,13 @@ LongLivedObjectCollection &LongLivedObjectCollection::get() {
|
|||
|
||||
LongLivedObjectCollection::LongLivedObjectCollection() {}
|
||||
|
||||
void LongLivedObjectCollection::add(std::shared_ptr<LongLivedObject> so) {
|
||||
void LongLivedObjectCollection::add(std::shared_ptr<LongLivedObject> so) const {
|
||||
std::lock_guard<std::mutex> lock(collectionMutex_);
|
||||
collection_.insert(so);
|
||||
}
|
||||
|
||||
void LongLivedObjectCollection::remove(const LongLivedObject *o) {
|
||||
void LongLivedObjectCollection::remove(const LongLivedObject *o) const {
|
||||
std::lock_guard<std::mutex> lock(collectionMutex_);
|
||||
auto p = collection_.begin();
|
||||
for (; p != collection_.end(); p++) {
|
||||
if (p->get() == o) {
|
||||
|
@ -34,7 +36,8 @@ void LongLivedObjectCollection::remove(const LongLivedObject *o) {
|
|||
}
|
||||
}
|
||||
|
||||
void LongLivedObjectCollection::clear() {
|
||||
void LongLivedObjectCollection::clear() const {
|
||||
std::lock_guard<std::mutex> lock(collectionMutex_);
|
||||
collection_.clear();
|
||||
}
|
||||
|
||||
|
|
|
@ -8,6 +8,7 @@
|
|||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace facebook {
|
||||
|
@ -32,7 +33,7 @@ class LongLivedObject {
|
|||
};
|
||||
|
||||
/**
|
||||
* A singleton collection for the `LongLivedObject`s.
|
||||
* A singleton, thread-safe, write-only collection for the `LongLivedObject`s.
|
||||
*/
|
||||
class LongLivedObjectCollection {
|
||||
public:
|
||||
|
@ -41,13 +42,14 @@ class LongLivedObjectCollection {
|
|||
LongLivedObjectCollection(LongLivedObjectCollection const &) = delete;
|
||||
void operator=(LongLivedObjectCollection const &) = delete;
|
||||
|
||||
void add(std::shared_ptr<LongLivedObject> o);
|
||||
void remove(const LongLivedObject *o);
|
||||
void clear();
|
||||
void add(std::shared_ptr<LongLivedObject> o) const;
|
||||
void remove(const LongLivedObject *o) const;
|
||||
void clear() const;
|
||||
|
||||
private:
|
||||
LongLivedObjectCollection();
|
||||
std::unordered_set<std::shared_ptr<LongLivedObject>> collection_;
|
||||
mutable std::unordered_set<std::shared_ptr<LongLivedObject>> collection_;
|
||||
mutable std::mutex collectionMutex_;
|
||||
};
|
||||
|
||||
} // namespace react
|
||||
|
|
Загрузка…
Ссылка в новой задаче