blob: 9157dca56b8e24780db6af9de27e638991e57571 [file] [log] [blame]
Brian Silverman26e4e522015-12-17 01:56:40 -05001/*----------------------------------------------------------------------------*/
2/* Copyright (c) FIRST 2008. All Rights Reserved.
3 */
4/* Open Source Software - may be modified and shared by FRC teams. The code */
5/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
6/*----------------------------------------------------------------------------*/
7
8#include "Task.h"
9
10#include "WPIErrors.h"
11#include <errno.h>
12#include <string.h>
13#include <stdio.h>
14
15#ifndef OK
16#define OK 0
17#endif /* OK */
18#ifndef ERROR
19#define ERROR (-1)
20#endif /* ERROR */
21
22const uint32_t Task::kDefaultPriority;
23
24Task& Task::operator=(Task&& task) {
25 m_thread.swap(task.m_thread);
26 m_taskName = std::move(task.m_taskName);
27
28 return *this;
29}
30
31Task::~Task() {
32 if (m_thread.joinable()) {
33 std::cout << "[HAL] Exited task " << m_taskName << std::endl;
34 }
35}
36
37bool Task::joinable() const noexcept {
38 return m_thread.joinable();
39}
40
41void Task::join() {
42 m_thread.join();
43}
44
45void Task::detach() {
46 m_thread.detach();
47}
48
49std::thread::id Task::get_id() const noexcept {
50 return m_thread.get_id();
51}
52
53std::thread::native_handle_type Task::native_handle() {
54 return m_thread.native_handle();
55}
56
57/**
58 * Verifies a task still exists.
59 *
60 * @return true on success.
61 */
62bool Task::Verify() {
63 TASK id = (TASK)m_thread.native_handle();
64 return verifyTaskID(id) == OK;
65}
66
67/**
68 * Gets the priority of a task.
69 *
70 * @return task priority or 0 if an error occured
71 */
72int32_t Task::GetPriority() {
73 int priority;
74 auto id = m_thread.native_handle();
75 if (HandleError(getTaskPriority(&id, &priority)))
76 return priority;
77 else
78 return 0;
79}
80
81/**
82 * This routine changes a task's priority to a specified priority.
83 * Priorities range from 1, the lowest priority, to 99, the highest priority.
84 * Default task priority is 60.
85 *
86 * @param priority The priority at which the internal thread should run.
87 * @return true on success.
88 */
89bool Task::SetPriority(int32_t priority) {
90 auto id = m_thread.native_handle();
91 return HandleError(setTaskPriority(&id, priority));
92}
93
94/**
95 * Returns the name of the task.
96 *
97 * @return The name of the task.
98 */
99std::string Task::GetName() const { return m_taskName; }
100
101/**
102 * Handles errors generated by task related code.
103 */
104bool Task::HandleError(STATUS results) {
105 if (results != ERROR) return true;
106 int errsv = errno;
107 if (errsv == HAL_taskLib_ILLEGAL_PRIORITY) {
108 wpi_setWPIErrorWithContext(TaskPriorityError, m_taskName.c_str());
109 } else {
110 printf("ERROR: errno=%i", errsv);
111 wpi_setWPIErrorWithContext(TaskError, m_taskName.c_str());
112 }
113 return false;
114}