• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 591
  • Last Modified:

TCriticalSection not working

Hi,

I made a little test program to test the working of critical sections, but it doesn't give the result I want.
I have 2 forms with each a button on.  When clicking buIncrease, the program counts from 0 to 100.  When it is counting and the couter is at 50 (eg) , i click on the button on the second form, wich calls the same function of when clicking the first button.  The result is that the label laThread1Status displays 0 to 50 and then counts from 0 to 100 (which is done by the second call), and when it reaches 100, it restarts counting from 50 to 100 (which is the first call that is resumed).
The criticalsection should make sure that the first call first has to be completed, no..?

void __fastcall TForm1::buIncreaseClick(TObject *Sender)
{
        int max = 100;
        csList->Acquire();   //TCriticalSection
        for(int i=0;i<max;i++)
        {
                laThread1Status->Caption = "running: "+IntToStr(i);
                laThread1Status->Repaint();
                Sleep(250);
                Application->ProcessMessages();
        }
        laThread1Status->Caption = "finished";
        laThread1Status->Repaint();
       csList->Release();
}

void __fastcall TForm2::Button2Click(TObject *Sender)
{
        Form1->buIncreaseClick(NULL);
}




0
cleaverX
Asked:
cleaverX
1 Solution
 
cleaverXAuthor Commented:
The critical section does not protect against "concurrent" access from within the same thread...
This has more to do with events I think...
how can i force a function to finish before this same function is called by an event...?
0
 
cwwkieCommented:
what is the declaration and initialisation of csList?
0
 
AdrianSRUCommented:
>The critical section does not protect against "concurrent" access from within the same thread.
cleaverX is correct.  Builder programs have a main VCL thread that the events run in.  Since both events are comming from the same thread, TCriticalSection will allow the second Acquire to complete before the first Release is called.

The solution to your problem is to use classes decended from TThread.  That way your synchronization will work fine.


--Adrian
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now