I can use created TThread object for more times? (C++ Builder environment)

132 Views Asked by At

Good morning, I would like to use a TThread object to process numeric values. On a recurring basis (through the TTimer object), different/updated values ​​are always presented in processing.

Basically:

  • The first time I create and launch the TThread which is actually executed but not deleted.
  • Subsequently (by TTimer), I get new values ​​for TThread to process.

Request:
Is there a way to "restart" the TThread with the new values, without creating a new TThread object every time? (TThread already exists)

This would save time, since the values ​​would always use the space allocated in the first TThread creation.

1

There are 1 best solutions below

0
On

A TThread (or any other kind of thread wrapper, for that matter) cannot be "restarted" once it has finished running. All you can do is free it.

So, to do what you are asking for, you would need to make the thread's Execute() method run a loop that processes your numeric values on each iteration as needed, until you are ready to signal the thread to terminate itself.

You will have to implement your own thread-safe system to push new numerics into the thread when needed, and to make the thread wait for new numerics to arrive between each loop iteration. For instance, you could push values into a TThreadList or TThreadedQueue, signaling a waitable TEvent or TMonitor on each push, and then the thread loop can wait on that signal before pulling values on each iteration.

Otherwise, consider using TTask instead of TThread. Tasks can utilize thread pooling internally, so you can just create a new TTask each time you have a new numeric to process, and let it pull out an available thread from the pool, and put the thread back in the pool when finished.