volatile uint32_t inventory = 100;
volatile uint32_t retailCount = 0;
volatile uint32_t onlineCount = 0;
SemaphoreHandle_t xMutexInventory = NULL;
TickType_t timeOut = 1000;
void retailTask(void *pvParam)
{
while (true)
{
if (xSemaphoreTake(xMutexInventory, timeOut) == pdPASS)
{
uint32_t inv = inventory;
for (int i = 0; i < random(1, 10); i++)
vTaskDelay(pdMS_TO_TICKS(i));
if (inventory > 0)
{
inventory = inv - 1;
retailCount++;
xSemaphoreGive(xMutexInventory);
}
else
{
xSemaphoreGive(xMutexInventory);
vTaskDelete(NULL);
}
}
vTaskDelay(10);
}
}
void onlineTask(void *pvParam)
{
while (true)
{
if (xSemaphoreTake(xMutexInventory, timeOut) == pdPASS)
{
// 以下实现了带有随机延迟的 inventory减1;
// 等效为 inventory--; retailCount++;
uint32_t inv = inventory;
for (int i; i < random(1, 10); i++)
vTaskDelay(pdMS_TO_TICKS(i));
if (inventory > 0)
{
inventory = inv - 1;
onlineCount++;
xSemaphoreGive(xMutexInventory);
}
else
{
xSemaphoreGive(xMutexInventory);
vTaskDelete(NULL);
}
}
vTaskDelay(10); // 老板要求慢一些,客户升级后,可以再加快速度
}
}
void showTask(void *pvParam)
{
while (true)
{
printf("Inventory: %d\n", inventory);
printf(" Retail : %d, Online : %d\n", retailCount, onlineCount);
if (inventory == 0)
{
uint32_t totalSales = retailCount + onlineCount;
printf("\n-----SALES SUMMARY-----\n");
printf(" Total Sales: %d\n\n", totalSales);
printf(" OverSales: %d\n", 100 - totalSales);
vTaskDelete(NULL);
}
vTaskDelay(pdMS_TO_TICKS(100));
}
}
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
xMutexInventory = xSemaphoreCreateMutex();
if (NULL == xMutexInventory)
{
printf("No Enough Ram, Unable to Create Semaphore.");
}
else
{
xTaskCreate(retailTask, "retailTask Channel", 1024 * 4, NULL, 1, NULL);
xTaskCreate(onlineTask, "Online Channel", 1024 * 4, NULL, 1, NULL);
xTaskCreate(showTask, "Display Inventory", 1024 * 4, NULL, 1, NULL);
}
}
void loop()
{
// put your main code here, to run repeatedly:
}