0

I have little problem with multithreading. I use CreateThread to create my own thread and create it when program starts (sorry but at this moment i cant use VCL threads). So my thread working with my VCL form. All program life second thread life too. But here one problem. When VCL form going to terminate my thread can check some form (class) params. Sure when my main form already terminated and some thread try to check methods in this form... then i got access violation.

How i can secured check params in my VCL form? Thanks!

here is my code.

unsigned int WINAPI CheckMutex( LPVOID lpParam )
{
    const int def = 20;
    int Cnt = def;
    UnicodeString text;
    while (1)
    {
        if (!UpdFrm || !UpdFrm->Label8 || UpdFrm->MutexTerminate)
            break;

first im checking pointer to UpdFrm but VCL form can be terminated but pointer to form still alive. So thats why i check some controls for existing. And only after that i check MutexTerminate

user922871
  • 435
  • 2
  • 6
  • 17
  • In the Form's destructor, you can set the `UdpFrm` variable to NULL. But that does not eliminate the race condition that `UdpFrm` could be non-NULL when you first check it and then become NULL before you can access its members. Why not just terminate the thread before the Form is freed? – Remy Lebeau May 04 '13 at 00:24

1 Answers1

0

But here one problem. When VCL form going to terminate my thread can check some form (class) params

Don't do this, for exactly the reason you have found. Do not access directly any form instance vars from your secondary worker threads.

If you have to communicate with GUI-thread VCL components, or TForm descendant instance vars, do so only via Windows messages, preferably PostMessaged to the form.

The only other way round this issue is to ensure that the secondary thread is terminated before the form instance is freed. This will lead you into a maze of twisty little deadlocks, all alike :(

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Martin James
  • 24,453
  • 3
  • 36
  • 60
  • thanks but can you explain a little bit more? So i have Form called "UpdFrm". In constructor i create new thread via "CreateThread". So i must send message by PostMessage to my owner thread? And what i must do if i only want to check veriable? Ofcourse i can move my thread to TThread class and use "Synchronize" method but this one solve my problem? Can you give me some example or book where i can read about this? Thanks for advise!! – user922871 May 02 '13 at 19:50
  • If you create the thread in the Form's constructor, then logically you could terminate the thread in the Form's destructor. That way, the Form pointer is never invalid while the thread is running. – Remy Lebeau May 04 '13 at 00:21
  • FYI, you don't need to switch your thread to `TThread` in order to use `Synchronize()`. `TThread` has static versions of `Synchronize()` that do not require a `TThread` object instance. – Remy Lebeau May 04 '13 at 00:23