Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion of thread synchronization problem

It makes me confused when I read the article by Zarko Gajic today:

"Multithreaded Delphi Database Queries"

Article URL: http://delphi.about.com/od/kbthread/a/query_threading.htm

Sourecode: http://delphi.about.com/library/weekly/code/adothreading.zip

With the code of "TCalcThread.Execute" procedure, Why the following code do not need to be placed in the Synchronize() method to run?

Line 173:    ListBox.Clear;  
Line 179:    ListBox.Items.Insert(......);
Line 188:    ListBox.Items.Add('*---------*');
Line 195:    TicksLabel.Caption := 'Ticks: ' + IntToStr(ticks);

These codes are operating the VCL components, and are related to the UI updates. In my knowledge, these operations should be use thread synchronize, and executed by the main thread. Is my knowledge has the flaw?

like image 641
Leo Avatar asked Jan 19 '10 01:01

Leo


People also ask

What are the risks of synchronization?

Synchronization risk arises from arbitrageur's uncertainty about when other arbitrageurs will start exploiting a common arbitrage opportunity (Abreu and Brunnermeier, 2002 and 2003). The arbitrage opportunity appears when prices move away from fundamental values.

What is the problem with synchronization of thread?

Synchronization can result in hold-wait deadlock where two threads each have the lock of an object, and are trying to acquire the lock of the other thread's object. Synchronization must also be global for a class, and an easy mistake to make is to forget to synchronize a method.


1 Answers

This is a rare case where you're benefiting from the fact that Windows is doing the thread synchronization for you. The reason is that for a listbox, the items are manipulated using SendMessage with control specific messages. Because of this, each SendMessage call makes sure the message is processed by the same thread on which the control was created, notably the main thread.

Like I said, this is a rare case. It is also causing a thread switch for each of those three calls, which will degrade performance. You're still better off using Synchronize to force that block of code to run in the main thread where it belongs. It also ensures that if you begin working with a control that doesn't internally use SendMessage, you won't get bitten.

like image 90
Allen Bauer Avatar answered Sep 28 '22 16:09

Allen Bauer