Files
react-native/ReactCommon/react/utils/ThreadStorage.h
T
David Vacca 08d7b542de Create Android OSS build system for react/utils module
Summary:
This diff creates the Android OSS build system for the module react/utils

As part of this diff I also moved the module to react/utils folder

changelog: [internal] internal

Reviewed By: JoshuaGross

Differential Revision: D22877265

fbshipit-source-id: 717487aacb392d0f08530763a16a638b8021d501
2020-08-05 19:02:08 -07:00

58 lines
1.3 KiB
C++

/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <better/map.h>
#include <better/optional.h>
#include <mutex>
#include <thread>
namespace facebook {
namespace react {
/*
* ThreadStorage is a class designed to store data for specific thread.
* When data is inserted from thread 1, it can only be retrieved from thread 1.
*/
template <typename DataT>
class ThreadStorage {
/*
* Private default constructor. This class has to be used as a singleton.
*/
ThreadStorage() = default;
public:
static ThreadStorage<DataT> &getInstance() {
static ThreadStorage<DataT> threadStorage;
return threadStorage;
}
better::optional<DataT> get() const {
std::lock_guard<std::mutex> lock(mutex_);
auto iterator = storage_.find(std::this_thread::get_id());
if (iterator != storage_.end()) {
return iterator->second;
} else {
return {};
}
}
void set(DataT data) {
std::lock_guard<std::mutex> lock(mutex_);
storage_[std::this_thread::get_id()] = data;
}
private:
mutable std::mutex mutex_;
better::map<std::thread::id, DataT> storage_;
};
} // namespace react
} // namespace facebook