This example demonstrates how to create and destroy threads dynamically at runtime.
extern "C" {
void __cxa_pure_virtual(void) {}
void DebugPrint(const char* szString_);
}
namespace
{
void App1Main(void* unused_);
void IdleMain(void* )
{
while (1) {}
}
#define MAX_THREADS (10)
Thread* apclActiveThreads[10];
uint32_t au32ActiveTime[10];
void PrintThreadSlack(void)
{
for (uint8_t i = 0; i < MAX_THREADS; i++) {
if (apclActiveThreads[i] != 0) {
char szStr[10];
}
}
}
void PrintCPUUsage(void)
{
for (int i = 0; i < MAX_THREADS; i++) {
if (apclActiveThreads[i] != 0) {
}
}
}
void ThreadCreate(
Thread* pclThread_)
{
{
for (uint8_t i = 0; i < MAX_THREADS; i++) {
if (apclActiveThreads[i] == 0) {
apclActiveThreads[i] = pclThread_;
break;
}
}
}
PrintThreadSlack();
PrintCPUUsage();
}
void ThreadExit(
Thread* pclThread_)
{
{
for (uint8_t i = 0; i < MAX_THREADS; i++) {
if (apclActiveThreads[i] == pclThread_) {
apclActiveThreads[i] = 0;
au32ActiveTime[i] = 0;
break;
}
}
}
PrintThreadSlack();
PrintCPUUsage();
}
void ThreadContextSwitch(
Thread* pclThread_)
{
static uint32_t u32LastTicks = 0;
{
for (uint8_t i = 0; i < MAX_THREADS; i++) {
if (apclActiveThreads[i] == pclThread_) {
au32ActiveTime[i] += u32Ticks - u32LastTicks;
break;
}
}
}
u32LastTicks = u32Ticks;
}
void WorkerMain1(void* arg_)
{
auto* pclSem =
static_cast<Semaphore*
>(arg_);
uint32_t u32Count = 0;
while (u32Count < 1000000) { u32Count++; }
pclSem->Post();
while (1) {}
}
void WorkerMain2(void* arg_)
{
uint32_t u32Count = 0;
while (u32Count < 1000000) { u32Count++; }
}
void App1Main(void* unused_)
{
while (1) {
clMyThread.
Init(awApp2Stack,
sizeof(awApp2Stack), 1, WorkerMain1, (
void*)&clMySem);
uint32_t u32Count = 0;
while (u32Count < 100000) { u32Count++; }
PrintThreadSlack();
clMySem.Pend();
clMyThread.
Init(awApp2Stack,
sizeof(awApp2Stack), 1, WorkerMain2, 0);
u32Count = 0;
while (u32Count < 1000000) { u32Count++; }
PrintThreadSlack();
}
}
}
int main(void)
{
clIdleThread.Init(awIdleStack, sizeof(awIdleStack), 0, IdleMain, 0);
clIdleThread.Start();
clApp1Thread.Init(awApp1Stack, sizeof(awApp1Stack), 1, App1Main, 0);
clApp1Thread.Start();
return 0;
}