diff --git a/SwitchUSB/include/SwitchThread.h b/SwitchUSB/include/SwitchThread.h new file mode 100644 index 0000000..89385cd --- /dev/null +++ b/SwitchUSB/include/SwitchThread.h @@ -0,0 +1,37 @@ +#pragma once +#include "switch.h" + +//Wrapper for switch thread implementation. Passed function will be called indefinitely until the thread closes. +class SwitchThread +{ +private: + Thread m_thread; + bool m_isRunning = false; + ThreadFunc m_function; + void *m_argument; + + static void ThreadLoop(void *argument); + +public: + SwitchThread() = default; + + //function - the function you want to be called + //argument - the argument passed to that function + //stackSize - the stack size of the created thread + //prio - thread priority, 0x00 - highest, 0x3F - lowest. Switch uses 0x2C + SwitchThread(ThreadFunc function, void *argument, size_t stackSize, int prio); + + //SwitchThread isn't copy-movable, because the memory address of its variables is important + SwitchThread &operator=(const SwitchThread &other) = delete; + SwitchThread &operator=(const SwitchThread &&other) = delete; + //Closes the thread upon exiting + ~SwitchThread(); + + //Starts the thread. This is called automatically upon class creation. + Result Start(); + + //This will block the caller indefinitely until the thread is returned! + Result Close(); + + bool inline IsRunning() { return m_isRunning; } +}; \ No newline at end of file diff --git a/SwitchUSB/source/SwitchThread.cpp b/SwitchUSB/source/SwitchThread.cpp new file mode 100644 index 0000000..6b6c4c4 --- /dev/null +++ b/SwitchUSB/source/SwitchThread.cpp @@ -0,0 +1,49 @@ +#include "SwitchThread.h" +#include "switch.h" + +void SwitchThread::ThreadLoop(void *argument) +{ + svcSleepThread(1e+7L); + while (static_cast(argument)->m_isRunning) + { + static_cast(argument)->m_function(static_cast(argument)->m_argument); + } +} + +SwitchThread::SwitchThread(ThreadFunc function, void *argument, size_t stackSize, int prio) + : m_function(function), m_argument(argument) +{ + if (R_SUCCEEDED(threadCreate(&m_thread, &SwitchThread::ThreadLoop, this, NULL, stackSize, prio, -2))) + { + Start(); + } +} + +SwitchThread::~SwitchThread() +{ + Close(); +} + +Result SwitchThread::Start() +{ + if (!m_isRunning) + { + m_isRunning = true; + return threadStart(&m_thread); + } + else + return 0; +} + +Result SwitchThread::Close() +{ + if (m_isRunning) + { + m_isRunning = false; + svcCancelSynchronization(m_thread.handle); + threadWaitForExit(&m_thread); + return threadClose(&m_thread); + } + else + return 0; +} \ No newline at end of file