Implement CreateAnonymousThread with BCC32.

Posted by on in Programming

C++Builder 10.2 BCC32 can not write lambda. 
So write an implementation in Invoke() with TCppInterfacedObject<>.

struct T_thread_proc :  TCppInterfacedObject<TProc>{
    TNotifyEvent f_ev_;
    struct T_sync_proc :  TCppInterfacedObject<TThreadProcedure>{
        TNotifyEvent f_ev_;
        T_sync_proc(TNotifyEvent& ev2){ f_ev_ = ev2; }
        virtual void __fastcall Invoke() {
            //Inside Synchronize.
            f_ev_(NULL);  //Execute "TNotifyEvent".
        }
    };
    T_thread_proc(TNotifyEvent ev1){f_ev_ = ev1; }
    virtual void __fastcall Invoke() {
        //Write thread execution code here.
        Sleep(3000); //example
        //Finally call Synchronize.
        TThread::Synchronize(
            TThread::CurrentThread,_di_TThreadProcedure(new T_sync_proc(f_ev_)));
    }
};

Event prepared for calling with TThread::Synchronize().

void __fastcall TForm1::do_thread_event(TObject *Sender)
{
    Button1->Enabled    = true;
    ActivityIndicator1->Visible = false;
    ActivityIndicator1->Animate = false;
    Caption = "End CreateAnonymousThread";
}

Call TThread::CreateAnonymousThread() with a TButton event.

Place the TButton and TActivityIndicator

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    TThread::CreateAnonymousThread(_di_TProc( new T_thread_proc(&do_thread_event)))->Start();
    Caption = "Started CreateAnonymousThread";
    ActivityIndicator1->Visible = true;
    ActivityIndicator1->Animate = true;
    Button1->Enabled    = false;
}

Build execution.

When you click the Button1, until the thread is finished "ActivityIndicator1->Animate = true";

 



About
Gold User, No rank,
Delphi / C++Builder blogger

Comments

  • David Millington
    David Millington Thursday, 14 September 2017

    Great code snippet. Also well worth noting that with the modern compilers we ship, a lot of this can be reduced to a one-liner via a lambda... Just one of the benefits of using the modern toolchain :)

  • haruyuki mohri
    haruyuki mohri Thursday, 14 September 2017

    David-san,
    It is a nice follow-up.
    Thank you.

  • Please login first in order for you to submit comments
  • Page :
  • 1

Check out more tips and tricks in this development video: