Remove spinning from AbandonableTask::Finish

This commit is contained in:
Tamás Bálint Misius 2019-03-13 21:55:45 +01:00 committed by jacob1
parent fc8740f7d5
commit e29e3481e0
2 changed files with 14 additions and 8 deletions

View File

@ -47,7 +47,7 @@ void AbandonableTask::Start()
pthread_create(&doWorkThread, 0, &AbandonableTask::doWork_helper, this); pthread_create(&doWorkThread, 0, &AbandonableTask::doWork_helper, this);
#ifdef DEBUGTHREADS #ifdef DEBUGTHREADS
std::cerr << "AbandonableTask @ " << this << " created" << std::endl; std::cerr << "AbandonableTask @ " << this << " created" << std::endl;
#endif #endif
} }
@ -57,6 +57,7 @@ TH_ENTRY_POINT void * AbandonableTask::doWork_helper(void * ref)
AbandonableTask *task = (AbandonableTask *)ref; AbandonableTask *task = (AbandonableTask *)ref;
pthread_mutex_lock(&task->taskMutex); pthread_mutex_lock(&task->taskMutex);
pthread_cond_signal(&task->done_cv);
bool abandoned = task->thAbandoned; bool abandoned = task->thAbandoned;
pthread_mutex_unlock(&task->taskMutex); pthread_mutex_unlock(&task->taskMutex);
if (abandoned) if (abandoned)
@ -78,15 +79,16 @@ TH_ENTRY_POINT void * AbandonableTask::doWork_helper(void * ref)
void AbandonableTask::Finish() void AbandonableTask::Finish()
{ {
// note to self: if you make this wait for a condition variable, pthread_mutex_lock(&taskMutex);
// lock the corresponding mutex before calling GetDone, otherwise while (!thDone)
// the CV may be signalled between the call and the locking of the
// mutex. -- LBPHacker
while (!GetDone())
{ {
Poll(); pthread_cond_wait(&done_cv, &taskMutex);
Platform::Millisleep(1);
} }
pthread_mutex_unlock(&taskMutex);
// Poll to make sure that the rest of the Task knows that it's
// done, not just us.
Poll();
#ifdef DEBUGTHREADS #ifdef DEBUGTHREADS
std::cerr << "AbandonableTask @ " << this << " finished" << std::endl; std::cerr << "AbandonableTask @ " << this << " finished" << std::endl;
@ -145,6 +147,7 @@ void AbandonableTask::Poll()
AbandonableTask::AbandonableTask() AbandonableTask::AbandonableTask()
{ {
pthread_cond_init(&done_cv, NULL);
#ifdef DEBUGTHREADS #ifdef DEBUGTHREADS
std::cerr << "AbandonableTask @ " << this << " ctor" << std::endl; std::cerr << "AbandonableTask @ " << this << " ctor" << std::endl;
#endif #endif
@ -162,5 +165,6 @@ AbandonableTask::~AbandonableTask()
std::cerr << "AbandonableTask @ " << this << " dtor" << std::endl; std::cerr << "AbandonableTask @ " << this << " dtor" << std::endl;
#endif #endif
pthread_cond_destroy(&done_cv);
} }

View File

@ -5,6 +5,8 @@
class AbandonableTask : public Task class AbandonableTask : public Task
{ {
pthread_cond_t done_cv;
public: public:
void Start() override; void Start() override;
void Finish(); void Finish();