ftrias / TeensyThreads

MIT License
182 stars 26 forks source link

Use with lambda? #8

Open mgcrea opened 6 years ago

mgcrea commented 6 years ago

I was looking for an easy way to do some javascript-like window.setTimeout behavior.

Looks like it's working using lambdas:

  threads.addThread(
      [](int tid) {
        delay(2000);
        Serial.print("TRIGGER=");
        Serial.println(tid);
      },
      1);

Question is, is it safe to use as is? Do I have to cleanup the threads somehow? Wanted to use this in a slow (but potentially infinite loop), so I'm wondering if I'm safe memory wise.

Thanks!

ftrias commented 6 years ago

I think that should be fine. The threads use static memory and don't need cleanup. This was done to avoid memory leaks--especially for beginners.

mgcrea commented 6 years ago

Thanks a lot! One final question not directly seen/understood in the readme, do you support [&]() or [=]() to pass values/references? Or do I have to only the arg?

I'm getting:

no instance of overloaded function "Threads::addThread" matches the argument list -- argument types are: (lambda []void (int frequency)->void, const int) -- object type is: Threads

Thanks again for the nice lib (and sorry if the question is dumb/answered).

ftrias commented 6 years ago

In your case, I believe the function it should match is:

int addThread(ThreadFunctionInt p, int arg=0, int stack_size=-1, void *stack=0);

And it's probably not matching because you are passing a "const int" instead of an "int". I don't recall why the argument in addThread isn't "const". It would seem like all the arguments should be "const" since the Thread library doesn't change them. I'll look into it.

In the meantime, try removing the "const" in your code and see what happens.

As for the captures [&], [=], etc. I really don't know as I haven't tested that. I suspect it's probably OK.

mgcrea commented 6 years ago

No more luck without the const:

With a single int:

 error: no matching function for call to 'Threads::addThread(Motor::toneMotor(int)::<lambda(int)>, int)'

Without args:

src/motor/motor.cpp:131:4: error: no matching function for call to 'Threads::addThread(Motor::toneMotor(int)::<lambda()>)'

Not blocking for me though as I can use the int arg to pass my argument.