volatile uint16_t inventory = 100;
volatile uint16_t retail_count = 0;
volatile uint16_t online_count = 0;

SemaphoreHandle_t mutexinventory = NULL;

TickType_t timeout = 1000;

void task_retail(void *pt)
{
  int inv = inventory;
  while (1)
  {
    if (xSemaphoreTake(mutexinventory, timeout) == pdPASS)
    {
      for (int i = 0; i < random(10, 100); i++)
      {
        vTaskDelay(i / portTICK_PERIOD_MS);
      }
      if (inventory > 0)
      {
        inventory = inv - 1;
        retail_count += 1;
        xSemaphoreGive(mutexinventory);
      }
    }
  }
}

void task_online(void *pt)
{
  int inv = inventory;
  while (1)
  {
    if (xSemaphoreTake(mutexinventory, timeout) == pdPASS)
    {
      for (int i = 0; i < random(10, 100); i++)
      {
        vTaskDelay(i / portTICK_PERIOD_MS);
      }
      if (inventory > 0)
      {
        inventory = inv - 1;
        online_count += 1;
        xSemaphoreGive(mutexinventory);
      }
    }
  }
}

void task_show(void *pt)
{
  while (1)
  {
    if(inventory > 0)
    {
      printf("inventory:%d, sale:%d\n", inventory, retail_count + online_count);
      printf("inventory empty, retail: %d, online: %d\n", retail_count, online_count);
    }
    else
    {
      printf("-------------\n");
      printf("inventory empty, retail: %d, online: %d\n", retail_count, online_count);
    }
    vTaskDelay(1000/portTICK_PERIOD_MS);
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  mutexinventory = xSemaphoreCreateMutex();
  if (mutexinventory == NULL)
  {
    Serial.println("mutex error");
  }
  else
  {
    Serial.println("mutex is created successfully");
    if (xTaskCreate(task_retail, "retail", 1024*4, NULL, 1, NULL) == pdPASS)
    {
      Serial.println("task retail is created successfully");
    }
    if (xTaskCreate(task_online, "online", 1024*4, NULL, 1, NULL) == pdPASS)
    {
      Serial.println("task online is created successfully");
    }
    if (xTaskCreate(task_show, "show", 1024*4, NULL, 1, NULL) == pdPASS)
    {
      Serial.println("task show is created successfully");
    }
  }
}

void loop() {
  // put your main code here, to run repeatedly:
}