Skip to content

empty loop(): Starves threads #132

Open
@KurtE

Description

@KurtE

Describe the bug
Suppose you have a sketch that does all of it's work in setup, which sets up interrupts and
one or more threads. And the sketch does nothing in loop()

The started threads appear to starve.

This is sort of an extract from earlier issue about trying to get touch events from the display shield.
I am currently testing it on GIGA, but suspect true of all of our boards.

Simple sketch:

#define STACKSIZE 4096
#define SLEEPTIME 500
#define PRIORITY 2

K_THREAD_STACK_DEFINE(blink_pins_thread_stack, STACKSIZE);

static struct k_thread blink_pins_thread_data;

void blink_pins_thread(void *dummy1, void *dummy2, void *dummy3)
{
	ARG_UNUSED(dummy1);
	ARG_UNUSED(dummy2);
	ARG_UNUSED(dummy3);

	Serial.print("thread_a: thread started \n");

	while (1)
	{
    static uint8_t pin_state = 0;
    pin_state ^=1;
    digitalWrite(LED_BUILTIN, pin_state);
  	k_msleep(SLEEPTIME);
  }
}

void setup() {
  Serial.begin(115200);
  while (!Serial && millis() < 5000)
    ;

  Serial.println("Thread Test started");
  pinMode(LED_BUILTIN, OUTPUT);
  
  // Start a thread:
    k_thread_create(&blink_pins_thread_data, blink_pins_thread_stack,
      K_THREAD_STACK_SIZEOF(blink_pins_thread_stack),
      blink_pins_thread, NULL, NULL, NULL,
      PRIORITY, 0, K_FOREVER);
  k_thread_name_set(&blink_pins_thread_data, "blink pins");

  Serial.print("Sketch Priority: ");
  Serial.println(k_thread_priority_get(k_sched_current_thread_query()));
  Serial.print("Cooperative: ");
  Serial.println(CONFIG_NUM_COOP_PRIORITIES);
  Serial.print("Preemptive: ");
  Serial.println(CONFIG_NUM_PREEMPT_PRIORITIES);

	k_thread_start(&blink_pins_thread_data);
}

void loop() {
}

Debug output:

Thread Test started
Sketch Priority: 0
Cooperative: 16
Preemptive: 15

Visually the LED comes on and never blinks.

Adding k_yield();
to loop does not help in this case.

adding a: delay(1);
And it blinks.

Suggestions:
Maybe the loop() thread should not be priority 0: Maybe should be something
near idle priority.

Maybe we could detect that it is not doing anything and put it to sleep for some period of time...

Or at minimum document it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions