Expose LambdaThread to public usage

I found myself in need of launching a lambda in its own Thread object, exactly like Thread::launch() does, but still having a Thread object to check for termination, etc.

I was about to wrap my own when noticed that Thread::launch() makes use of the following class defined in the cpp:

struct LambdaThread  : public Thread
    LambdaThread (std::function<void()> f) : Thread ("anonymous"), fn (f) {}

    void run() override
        fn = nullptr; // free any objects that the lambda might contain while the thread is still active

    std::function<void()> fn;


that would perfectly suit my needs, any chance to have it exposed for public use?
I don’t see any drawbacks and that would prevent some wheel reinvention, thanks.

Oh, and its constructor should also accept a boolean to determine whether the thread should auto-delete itself when terminated.

I’ve noticed that otherwise that feature is impossible to obtain, because deleteOnThreadEnd is private to Thread.

Thread::launch() always sets it, but a publicly available LambdaThread should probably benefit from both possibilities.

I’m not totally sure of your use-case, but have you considered using a ThreadPool (whose addJob method supports lambdas)?

Yes, considered that and it feels kinda overkill.

According to what the JUCE team says regarding exposing LambdaThread, I’ll go one route or the other.

Can’t you use Thread::currentThreadShouldExit()?

No, my need is to call waitForThreadToExit() on the spawned thread from the main thread, because I need the timeout that comes with it and the information regarding whether it succeeded in time or not.

a second option would be to have an overload of Thread::launch() that does exactly that, with a timeout parameter

I’m sorry, but… what appears to be the drawback of exposing LambdaThread?

To me it looks like a useful class that is also very tidy and simple, not a mere “implementation detail” subject to future fiddling that needs to be hidden.

If deleteOnThreadEnd was a feature publicly available, I would have rewritten that class for my usage exactly like that.

1 Like