ftrias / TeensyThreads

MIT License
182 stars 26 forks source link

Teensy 4.1 - simple code won't work #41

Open mateusz-kusmierz opened 1 year ago

mateusz-kusmierz commented 1 year ago

I've tried running teensyThreads, so I made below code as proof of concept, but it does not work correctly. Whats the issue?

#include <TeensyThreads.h>

volatile int counter1 = 0;
volatile int counter2 = 0;
volatile int counter3 = 0;

void thread1_func() {
  while(1) 
  {
    Serial.printf("thread 1 => %d\n",counter1++);
    delay(5000);
  }
}

void thread2_func() {
  while(1) 
  {
    Serial.printf("thread 2 => %d\n",counter2++);
    delay(500);
  }
}

void setup() {
  Serial.begin(115200);

  threads.addThread(thread1_func);
  threads.addThread(thread2_func);
}

void loop() 
{
Serial.printf("loop => %d\n",counter3++);
delay(2000);
}

Serial Monitor output:

thread 1 => 0
thread 2 => 0
loop => 1
loop => 2
loop => 3
loop => 4
loop => 5
loop => 6
loop => 7
loop => 8
loop => 9
loop => 10
loop => 11
loop => 12
loop => 13
loop => 14
loop => 15
loop => 16
loop => 17
loop => 18
loop => 19
loop => 20
loop => 21
loop => 22
abadiet commented 1 year ago

I guess the error comes from the use ofdelay () in a thread func. I thinkdelay () act on the main thread. Try threads.delay () instead.

mateusz-kusmierz commented 1 year ago

Thank You for Your response. I've tried that but unfortunately result is exactly the same.

Najib-Kassab commented 1 year ago

Same here, the tasks only run once and then never called again. @mateusz-kusmierz is there any updates?

Najib-Kassab commented 1 year ago

@mateusz-kusmierz well, I think I know where the issue is, I believe that you need you to increase the stack size to at least 2048. when I increased the stack size the program works fine.

Merlin04 commented 1 year ago

Yeah, I just ran into this exact same issue and finally figured out that for some reason Serial.printf requires a larger stack than 1k - this should be documented somewhere, I think that would be a pretty common function to use in a thread.

karelv commented 11 months ago

Is the Serial code thread-safe? Maybe use a mutex to lock the resource to the thread...

karelv commented 11 months ago

Yeah, I just ran into this exact same issue and finally figured out that for some reason Serial.printf requires a larger stack than 1k - this should be documented somewhere, I think that would be a pretty common function to use in a thread.

How do you increase the stack size on teensy 4.1?