How to proper terminate a thread?

Discussion and questions about programming with Ultibo.
pik33
Posts: 862
Joined: Fri Sep 30, 2016 6:30 pm
Location: Poland
Contact:

How to proper terminate a thread?

Postby pik33 » Thu Dec 27, 2018 9:35 am

I have a thread for experimenting with the camera. It runs at the realtime (=7) priority. It has FreeOnTerminate := True; . Then, at the end of the execute procedure there is self.Terminate; call

This doesn't work 100% as expected: if I run the opengl test after the camera test, it is very slow, as if the camera thread is still running at the realtime priority, consuming resources.
The workaround I used was to set the camera thread priority to 1 before call terminate, but this is no solution if this thread is still running, only at lowest priority.

The question is: what is a proper command sequence for a thread to shut off itself completely and don't leave any traces in the scheduler?

The threads I use are

type TCameraThread2=class (TThread)
User avatar
Ultibo
Site Admin
Posts: 2224
Joined: Sat Dec 19, 2015 3:49 am
Location: Australia

Re: How to proper terminate a thread?

Postby Ultibo » Thu Dec 27, 2018 10:59 pm

pik33 wrote:The question is: what is a proper command sequence for a thread to shut off itself completely and don't leave any traces in the scheduler?

The proper way to terminate a TThread (or descendant) is to simply exit the Execute procedure either by letting it exit out the end of the procedure or by calling Exit somewhere within the procedure.

Calling Terminate only sets the Terminated property and doesn't actually do anything itself, Terminate is normally called by another thread to tell the thread to it should terminate.

Looking at your TCameraThread2.execute procedure I can see the call to Terminate is last so if the thread reaches that point it should immediately exit from the procedure on the next line and terminate itself automatically.

Are you sure the thread is reaching the end of the Execute procedure?

Is this reproducible if we copy the TCameraThread2 out to a new unit and strip out any other functionality or can you make a reproducible case for us to test?
Ultibo.org | Make something amazing
https://ultibo.org
pik33
Posts: 862
Joined: Fri Sep 30, 2016 6:30 pm
Location: Poland
Contact:

Re: How to proper terminate a thread?

Postby pik33 » Fri Dec 28, 2018 7:24 am

I will investigate the topic further. I thought I have to do something to fully terminate the thread, which I simply don't know.
The call to terminate was one of these test ('maybe I have to call terminate?' ) I also tried 'destroy' there which immediately hanged the system.
This means I need a cleaner testing environment with only camera and opengl running

Return to “General”

Who is online

Users browsing this forum: No registered users and 1 guest