Libusbpp icon indicating copy to clipboard operation
Libusbpp copied to clipboard

Thread-unsafe code

Open gggrafff opened this issue 4 years ago • 0 comments

https://github.com/zarthcode/Libusbpp/blob/389ceea9bc974f1c2b1cf3151a32795c04832288/src/TransferImpl.hpp#L142

This field is static. Access to change it is shared by all objects of the class. Creating multiple objects in different threads results in a data race.

Please use a mutex and encapsulate operations with this field.

Example:

using TransferStorage = std::map<TransferImpl*, std::weak_ptr<TransferImpl>>;
static TransferStorage m_TransferMap;
static std::mutex m_TransferMap_mutex;

template<class T>
static std::pair<TransferStorage::iterator, bool> insert_transfer(T&& value) {
  std::lock_guard<std::mutex> lk(m_TransferMap_mutex);
  return m_TransferMap.insert(std::move(value));
}

static size_t erase_transfer(TransferImpl* index) {
  std::lock_guard<std::mutex> lk(m_TransferMap_mutex);
  return m_TransferMap.erase(index);
}

static std::weak_ptr<TransferImpl> get_transfer(TransferImpl* index) {
  std::lock_guard<std::mutex> lk(m_TransferMap_mutex);
  return m_TransferMap[index];
}

gggrafff avatar Jul 13 '20 13:07 gggrafff