Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-06-07 02:29:33

0001 #include "FWCore/Concurrency/interface/WaitingThreadPool.h"
0002 
0003 #include <cassert>
0004 #include <string_view>
0005 
0006 #include <pthread.h>
0007 
0008 namespace edm::impl {
0009   WaitingThread::WaitingThread() {
0010     thread_ = std::thread(&WaitingThread::threadLoop, this);
0011     static constexpr auto poolName = "edm async pool";
0012     // pthread_setname_np() string length is limited to 16 characters,
0013     // including the null termination
0014     static_assert(std::string_view(poolName).size() < 16);
0015 
0016     int err = pthread_setname_np(thread_.native_handle(), poolName);
0017     // According to the glibc documentation, the only error
0018     // pthread_setname_np() can return is about the argument C-string
0019     // being too long. We already check above the C-string is shorter
0020     // than the limit was at the time of writing. In order to capture
0021     // if the limit shortens, or other error conditions get added,
0022     // let's assert() anyway (exception feels overkill)
0023     assert(err == 0);
0024   }
0025 
0026   WaitingThread::~WaitingThread() noexcept {
0027     // When we are shutting down, we don't care about any possible
0028     // system errors anymore
0029     CMS_SA_ALLOW try {
0030       stopThread();
0031       thread_.join();
0032     } catch (...) {
0033     }
0034   }
0035 
0036   void WaitingThread::threadLoop() noexcept {
0037     std::unique_lock lk(mutex_);
0038 
0039     while (true) {
0040       cond_.wait(lk, [this]() { return static_cast<bool>(func_) or stopThread_; });
0041       if (stopThread_) {
0042         // There should be no way to stop the thread when it as the
0043         // func_ assigned, but let's make sure
0044         assert(not thisPtr_);
0045         break;
0046       }
0047       func_();
0048       // Must return this WaitingThread to the ReusableObjectHolder in
0049       // the WaitingThreadPool before resettting func_ (that holds the
0050       // WaitingTaskWithArenaHolder, that enables the progress in the
0051       // TBB thread pool) in order to meet the requirement of
0052       // ReusableObjectHolder destructor that there are no outstanding
0053       // objects.
0054       thisPtr_.reset();
0055       decltype(func_)().swap(func_);
0056     }
0057   }
0058 }  // namespace edm::impl