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:
Kevin Gozali 2019-09-27 13:42:45 -07:00 коммит произвёл Facebook Github Bot
Родитель de17cdecd8
Коммит 1452954c4c
2 изменённых файлов: 13 добавлений и 8 удалений

Просмотреть файл

@ -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