diff --git a/src/TransferImpl.cpp b/src/TransferImpl.cpp index e471350..2c2588b 100644 --- a/src/TransferImpl.cpp +++ b/src/TransferImpl.cpp @@ -109,7 +109,7 @@ void LibUSB::TransferImpl::Start() } // 3. Ensure that the callback can reach this transfer. - m_TransferMap.insert(make_pair(this, shared_from_this())); + InsertTransfer(make_pair(this, shared_from_this())); // 4. Submit the transfer int Result = libusb_submit_transfer(m_pTransfer.get()); @@ -225,7 +225,8 @@ void LibUSB::TransferImpl::AsyncTransferCallback( libusb_transfer* pTransfer ) TransferImpl* index = (TransferImpl*) pTransfer->user_data; /// Obtain the transfer's shared_ptr - m_TransferMap[index].lock()->NotifyComplete(); + auto transfer = GetTransfer(index); + transfer.lock()->NotifyComplete(); } @@ -248,7 +249,7 @@ void LibUSB::TransferImpl::NotifyComplete() // Remove the TransferMap entry. - m_TransferMap.erase(this); + EraseTransfer(this); } void LibUSB::TransferImpl::Reset() @@ -462,7 +463,8 @@ LibUSB::TransferResult_t LibUSB::TransferImpl::Result() const } -std::map> LibUSB::TransferImpl::m_TransferMap; +LibUSB::TransferImpl::TransferStorage LibUSB::TransferImpl::m_TransferMap; +std::mutex LibUSB::TransferImpl::m_TransferMap_mutex; // ********************************** diff --git a/src/TransferImpl.hpp b/src/TransferImpl.hpp index bf71a6a..c722851 100644 --- a/src/TransferImpl.hpp +++ b/src/TransferImpl.hpp @@ -137,9 +137,29 @@ namespace LibUSB private: - /// Weak pointers to all active transfer objects - static std::map> m_TransferMap; + using TransferStorage = std::map>; + static TransferStorage m_TransferMap; + static std::mutex m_TransferMap_mutex; + + /// Adding a new transfer object to the storage. + template + inline static std::pair InsertTransfer(T&& value) { + std::lock_guard lk(m_TransferMap_mutex); + return m_TransferMap.insert(std::move(value)); + } + + /// Deleting an transfer object from storage. + inline static size_t EraseTransfer(TransferImpl* index) { + std::lock_guard lk(m_TransferMap_mutex); + return m_TransferMap.erase(index); + } + + /// Retrieving an transfer object from storage. + inline static std::weak_ptr GetTransfer(TransferImpl* index) { + std::lock_guard lk(m_TransferMap_mutex); + return m_TransferMap[index]; + } /// Pointer to the Parent Transfer object std::weak_ptr m_pParentTransfer;