Skip to content

Commit

Permalink
Optimize named timer's lock logic.
Browse files Browse the repository at this point in the history
  • Loading branch information
Barenboim committed Oct 16, 2023
1 parent c4049c0 commit fdab1f0
Showing 1 changed file with 20 additions and 38 deletions.
58 changes: 20 additions & 38 deletions src/factory/WFTaskFactory.cc
Original file line number Diff line number Diff line change
Expand Up @@ -178,70 +178,52 @@ class __WFNamedTimerTask : public __WFTimerTask
__NamedTimerMap::TimerList *timers,
CommScheduler *scheduler,
timer_callback_t&& cb) :
__WFTimerTask(seconds, nanoseconds, scheduler, std::move(cb))
__WFTimerTask(seconds, nanoseconds, scheduler, std::move(cb)),
flag_(false)
{
dispatched_ = false;
node_.task = this;
timers->push_back(&node_);
timers_ = timers;
}

virtual ~__WFNamedTimerTask()
{
if (!dispatched_)
{
__timer_map.mutex_.lock();
if (node_.task)
timers_->del(&node_, &__timer_map.root_);

__timer_map.mutex_.unlock();
}
}

protected:
virtual void dispatch();
virtual void handle(int state, int error);

private:
bool dispatched_;
struct __timer_node node_;
__NamedTimerMap::TimerList *timers_;
std::atomic<bool> flag_;
std::mutex mutex_;
friend class __NamedTimerMap;
};

void __WFNamedTimerTask::dispatch()
{
int ret;

__timer_map.mutex_.lock();
mutex_.lock();
ret = this->scheduler->sleep(this);
if (ret < 0)
{
if (node_.task)
timers_->del(&node_, &__timer_map.root_);
}
else
{
if (!node_.task)
this->cancel();
}
if (ret >= 0 && flag_.exchange(true))
this->cancel();

dispatched_ = true;
__timer_map.mutex_.unlock();
mutex_.unlock();
if (ret < 0)
this->__WFTimerTask::handle(SS_STATE_ERROR, errno);
this->handle(SS_STATE_ERROR, errno);
}

void __WFNamedTimerTask::handle(int state, int error)
{
__timer_map.mutex_.lock();
if (node_.task)
timers_->del(&node_, &__timer_map.root_);
{
std::lock_guard<std::mutex> lock(__timer_map.mutex_);
if (node_.task)
timers_->del(&node_, &__timer_map.root_);
}

__timer_map.mutex_.unlock();
this->state = state;
this->error = error;
this->subtask_done();
mutex_.lock();
mutex_.unlock();
this->__WFTimerTask::handle(state, error);
}

WFTimerTask *__NamedTimerMap::create(const std::string& name,
Expand Down Expand Up @@ -272,7 +254,7 @@ void __NamedTimerMap::cancel(const std::string& name, size_t max)

node = list_entry(timers->head.next, struct __timer_node, list);
list_del(&node->list);
if (node->task->dispatched_)
if (node->task->flag_.exchange(true))
node->task->cancel();

node->task = NULL;
Expand Down Expand Up @@ -372,8 +354,8 @@ class __WFNamedCounterTask : public WFCounterTask
};

WFCounterTask *__NamedCounterMap::create(const std::string& name,
unsigned int target_value,
counter_callback_t&& cb)
unsigned int target_value,
counter_callback_t&& cb)
{
CounterList *counters;

Expand Down

0 comments on commit fdab1f0

Please sign in to comment.