blob: fa7349006b31acb8044e66804479b257da3be7a0 [file] [log] [blame]
Jeff Thompsonfa306642013-06-17 15:06:57 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2013, Regents of the University of California
4 * Alexander Afanasyev
5 * Zhenkai Zhu
6 *
7 * BSD license, See the LICENSE file for more information
8 *
9 * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
10 * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
11 */
12
13#include "task.h"
14#include "scheduler.h"
15
16static void
17eventCallback(evutil_socket_t fd, short what, void *arg)
18{
19 Task *task = static_cast<Task *>(arg);
20 task->execute();
21 task = NULL;
22}
23
24Task::Task(const Callback &callback, const Tag &tag, const SchedulerPtr &scheduler)
25 : m_callback(callback)
26 , m_tag(tag)
27 , m_scheduler(scheduler)
28 , m_invoked(false)
29 , m_event(NULL)
30 , m_tv(NULL)
31{
32 m_event = evtimer_new(scheduler->base(), eventCallback, this);
33 m_tv = new timeval;
34}
35
36Task::~Task()
37{
38 if (m_event != NULL)
39 {
40 event_free(m_event);
41 m_event = NULL;
42 }
43
44 if (m_tv != NULL)
45 {
46 delete m_tv;
47 m_tv = NULL;
48 }
49}
50
51void
52Task::setTv(double delay)
53{
54 // Alex: when using abs function, i would recommend use it with std:: prefix, otherwise
55 // the standard one may be used, which converts everything to INT, making a lot of problems
56 double intPart, fraction;
57 fraction = modf(std::abs(delay), &intPart);
58
59 m_tv->tv_sec = static_cast<int>(intPart);
60 m_tv->tv_usec = static_cast<int>((fraction * 1000000));
61}
62
63void
64Task::execute()
65{
66 // m_scheduler->execute(boost::bind(&Task::run, this));
67
68 // using a shared_ptr of this to ensure that when invoked from executor
69 // the task object still exists
70 // otherwise, it could be the case that the run() is to be executed, but before it
71 // could finish, the TaskPtr gets deleted from scheduler and the task object
72 // gets destroyed, causing crash
73 m_scheduler->execute(boost::bind(&Task::run, shared_from_this()));
74}