volatile uint32_t inventory = 100;
volatile uint32_t retailCount = 10;
volatile uint32_t onlineCount = 0;
void retailTask(void* pvParam)
{
while(true)
{
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++;
}
else
{
vTaskDelete(NULL);
}
vTaskDelay(10);
}
}
void onlineTask(void *pvParam) {
while (true)
{
//以下实现了带有随机延迟的 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++;
}
else
{
vTaskDelete(NULL);
}
vTaskDelay(10); //老板要求慢一些,客户升级后,可以再加快速度
}
}
void showTask(void* pvParam)
{
while(true)
{
printf("Inventory: %d\n", inventory);
printf(" Retail : %d\n", retailCount);
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);
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:
}