<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The Programming Works</title>
	<atom:link href="http://sergworks.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://sergworks.wordpress.com</link>
	<description>Delphi programming and more</description>
	<lastBuildDate>Fri, 27 Jan 2012 23:03:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='sergworks.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>The Programming Works</title>
		<link>http://sergworks.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://sergworks.wordpress.com/osd.xml" title="The Programming Works" />
	<atom:link rel='hub' href='http://sergworks.wordpress.com/?pushpress=hub'/>
		<item>
		<title>On the Delphi documentation issues</title>
		<link>http://sergworks.wordpress.com/2012/01/27/on-the-delphi-documentation-issues/</link>
		<comments>http://sergworks.wordpress.com/2012/01/27/on-the-delphi-documentation-issues/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 09:32:07 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Rant]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=614</guid>
		<description><![CDATA[Delphi XE2 documentation states: &#8216;Packed&#8217; Now Forces Byte Alignment of Records If you have legacy code that uses the packed record type and you want to link with an external DLL or with C++, you need to remove the word &#8220;packed&#8221; from your code. The packed keyword now forces byte alignment, whereas in the past [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=614&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Delphi XE2 <a href="http://docwiki.embarcadero.com/RADStudio/XE2/en/Delphi_Compiler_Changes_for_XE2#.27Packed.27_Now_Forces_Byte_Alignment_of_Records">documentation</a> states:</p>
<blockquote><p>&#8216;Packed&#8217; Now Forces Byte Alignment of Records</p>
<p>If you have legacy code that uses the packed record type and you want to link with an external DLL or with C++, you need to remove the word &#8220;packed&#8221; from your code. The packed keyword now forces byte alignment, whereas in the past it did not necessarily do this. The behavior change is related to C++ alignment compatibility changes in Delphi 2009.
</p></blockquote>
<p>The above cannot be classified even as a documentation bug; it is just a nonsense. There was a related <a href="http://stackoverflow.com/questions/8460862/what-does-packed-now-forces-byte-alignment-of-records-mean">StackOverflow</a> question. The question remained unanswered because it is impossible to answer it reasonably. Now more than a month passed, and the documentation issue is still there &#8211; the documentation writers definitely don&#8217;t read SO.</p>
<p>The best reading about Delphi alignment rules that I know is the <a href="http://stackoverflow.com/questions/4583985/are-where-any-difference-between-array-and-packed-array-in-delphi/4584293#4584293">Barry Kelly answer on SO</a>.</p>
<p>Let us try to analyze what the documentation is about.</p>
<li><em>The behavior change is related to C++ alignment compatibility changes in Delphi 2009</em></li>
<p>Delphi 2009 fixed a bug that caused different layout for</p>
<p><pre class="brush: delphi;">
type
  TRec = record
    A, B: Extended;
  end;
</pre></p>
<p>and</p>
<p><pre class="brush: delphi;">
type
  TRec = record
    A: Extended;
    B: Extended;
  end;
</pre></p>
<p>records in the previous versions, and introduced <a href="http://docwiki.embarcadero.com/RADStudio/en/Internal_Data_Formats#Implicit_Packing_of_Fields_with_a_Common_Type_Specification">{$OLDTYPELAYOUT ON}</a> directive to reproduce the alignment bug for compatibility reasons.</p>
<p>Hard to explain how that is related to <em>&#8216;Packed&#8217; Now Forces Byte Alignment of Records</em>.</p>
<li><em>The packed keyword now forces byte alignment, whereas in the past it did not necessarily do this</em></li>
<p>Seems like nobody can say now what <em>the past</em> the documentation writer is talking about. Maybe ages ago first Turbo Pascal versions treated external type alignment and internal record layout differently. Or maybe where was some bug in <em>packed</em> specifier implementation that nobody was ever aware of, and the bug was fixed ages ago &#8211; one can only guess. </p>
<li><em>If you have legacy code that uses the packed record type and you want to link with an external DLL or with C++, you need to remove the word &#8220;packed&#8221; from your code</em></li>
<p>If so, what is the Delphi equivalent of <em>#pragma pack(1)</em> in C/C++? Maybe the documentation writer suggests to use <em>{$A1}</em> or <em>{$A-}</em> directives instead of <em>packed</em> specifier? But <em>{$A1}</em>, <em>{$A-}</em> directives and <em>packed</em> specifier do exactly the same thing &#8211; force byte alignment. There is no difference here. Or maybe <em>#pragma pack(1)</em> in C/C++ affects only internal structure layout and not structure alignment?</p>
<p>Just to be sure I have tested the following code sample in Visual Studio 2010:</p>
<p><pre class="brush: cpp;">
struct S {
   short j;    // size 2
   double k;   // size 8
};

#pragma pack(1)	// force byte alignment
struct T {
   short j;
   double k;
};

#pragma pack() // restore default alignment
struct S1{
    char cc;       // size 1
    S ss;          // size 16
};

struct T1{
    char cc;       // size 1
    T tt;          // size 10
};

int _tmain(int argc, _TCHAR* argv[])
{
   printf(&quot;%d %d\n&quot;, sizeof(S), offsetof(S, k));        // 16 8
   printf(&quot;%d %d\n&quot;, sizeof(T), offsetof(T, k));        // 10 2

   printf(&quot;%d %d\n&quot;, sizeof(S1), offsetof(S1, ss));     // 24 8
   printf(&quot;%d %d\n&quot;, sizeof(T1), offsetof(T1, tt));     // 11 1

   _getch();
   return 0;
}
</pre></p>
<p>As you can see <em>#pragma pack(1)</em> forces byte alignment for both <em>T</em> structure fields and <em>T</em> structure as a whole, exactly the same thing as <em>packed</em> specifier in Delphi do.</p>
<p><strong>So what the documentation writer is talking about ?</strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/614/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/614/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/614/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/614/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/614/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/614/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/614/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/614/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/614/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/614/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/614/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/614/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/614/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/614/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=614&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2012/01/27/on-the-delphi-documentation-issues/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>
	</item>
		<item>
		<title>On the type compatibility in Delphi</title>
		<link>http://sergworks.wordpress.com/2012/01/12/on-the-type-compatibility-in-delphi/</link>
		<comments>http://sergworks.wordpress.com/2012/01/12/on-the-type-compatibility-in-delphi/#comments</comments>
		<pubDate>Thu, 12 Jan 2012 16:08:44 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[musings]]></category>
		<category><![CDATA[type compatibility]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=605</guid>
		<description><![CDATA[Delphi compiler evolves much faster than Delphi documentation, and some language features remain unnamed. Consider the following code snippet: The documentation states that MyPChar1 and PChar are identical types, while MyPChar2 and MyPChar3 are distinct; that is why Test(Ch2); and Test(Ch3); lines does not compile. But notice &#8211; the compiler issues different error codes. Does [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=605&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Delphi compiler evolves much faster than Delphi documentation, and some language features remain unnamed. Consider the following code snippet:</p>
<p><pre class="brush: delphi;">
type
  MyPChar1 = PChar;
  MyPChar2 = type PChar;
  MyPChar3 = ^Char;

procedure Test(Ch: PChar);
begin
end;

procedure TForm1.Button4Click(Sender: TObject);
var
  Ch1: MyPChar1;
  Ch2: MyPChar2;
  Ch3: MyPChar3;

begin
  Test(Ch1);
//  Test(Ch2);     Error E2008 Incompatible types
//  Test(Ch3);     Error E2010 Incompatible types: 'Unit1.Char' and 'System.Char'
end;
</pre><br />
The <a href="http://docwiki.embarcadero.com/RADStudio/en/Type_Compatibility_and_Identity">documentation</a> states that <em>MyPChar1</em> and <em>PChar</em> are identical types, while <em>MyPChar2</em> and <em>MyPChar3</em> are distinct; that is why <em>Test(Ch2);</em> and <em>Test(Ch3);</em> lines does not compile. But notice &#8211; the compiler issues different error codes. Does it matter?</p>
<p>Consider the next snippet:<br />
<pre class="brush: delphi;">
procedure Test1(Ch: MyPChar1);
begin
end;

procedure Test2(Ch: MyPChar2);
begin
end;

procedure Test3(Ch: MyPChar3);
begin
end;

procedure TForm1.Button5Click(Sender: TObject);
begin
  Test1('Foo');
  Test2('Foo');   // Compiles
//  Test3('Foo');    Error E2010 Incompatible types: 'MyPChar3' and 'string'
end;
</pre></p>
<p>The documentation states that <em>PChar</em> type is assignment compatible on input with string literal. It appears that there is a difference in type &#8216;distinctness&#8217;. The <em>type PChar</em> type is somewhat more compatible with <em>PChar</em> than <em>^Char</em> type.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/605/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/605/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/605/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/605/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/605/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/605/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/605/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/605/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/605/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/605/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/605/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/605/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/605/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/605/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=605&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2012/01/12/on-the-type-compatibility-in-delphi/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>
	</item>
		<item>
		<title>TThread Facts</title>
		<link>http://sergworks.wordpress.com/2011/12/18/tthread-facts/</link>
		<comments>http://sergworks.wordpress.com/2011/12/18/tthread-facts/#comments</comments>
		<pubDate>Sun, 18 Dec 2011 05:37:14 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Threads]]></category>
		<category><![CDATA[TThread]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=582</guid>
		<description><![CDATA[Delphi RTL TThread class has been an object of criticism since its introduction. Some criticism was deserved, some not. TThread implementation was gradually improving with every Delphi version. Here I am neither criticizing nor advocating the TThread class, just listing some details of TThread implementation in modern Delphi versions that Delphi programmer should know. TThread [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=582&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Delphi RTL TThread class has been an object of criticism since its introduction. Some criticism was deserved, some not. TThread implementation was gradually improving with every Delphi version. Here I am neither criticizing nor advocating the TThread class, just listing some details of TThread implementation in modern Delphi versions that Delphi programmer should know.</p>
<ol>
<li>TThread class does not allow setting a thread stack size – it is always equal to default value, usually 1 Mb.  If you need a different value you can call <em>BeginThread</em> function directly, but that is a low level solution and not as handy as using TThread class;</li>
<li>
TThread constructor has the only parameter (<em>CreateSuspended: Boolean</em>). Irrespective of the parameter value the underlying Windows thread object is always created in suspended state:<br />
<pre class="brush: delphi; gutter: false;">
    FCreateSuspended := CreateSuspended {...};
    FHandle := BeginThread(nil, 0, @ThreadProc, Pointer(Self), CREATE_SUSPENDED, FThreadID);
</pre><br />
A thread can start execution in <em>AfterConstruction</em> method (which is called after all inherited constructors):<br />
<pre class="brush: delphi; gutter: false;">
  if not FCreateSuspended {...} then Resume;
</pre><br />
or later;
</li>
<li>Synchronization with the main thread does not work in console application. That means that you should not use <em>Synchronize</em> and <em>Queue</em> methods of TThreads class in console application. The same also applies to <em>OnTerminate</em> event which calls <em>Synchronize</em> method internally; you can override protected <em>DoTerminate</em> method instead;</li>
<li>If you set <em>FreeOnTerminate = True</em> for a TThread instance, the instance is destroyed in the context of underlying background thread. Usually the destruction context does not matter, but in some cases it does. For example, create a TTimer instance in the constructor of TThread descendant, destroy timer in the destructor and see what happens (hint: an invisible window of TTimer instance is created in the main thread and destroyed in a different thread);</li>
<li>TThread does not guarantee that <em>Execute</em> method will be called. I have <a href="http://sergworks.wordpress.com/2011/06/25/sleep-sort-and-tthread-corner-case/" title="Sleep sort and TThread corner case">bumped into this problem</a> a little before.</li>
</ol>
<p>Despite all issues we are better to use TThread class ‘as is’ in GUI applications. For my experiments I have written a simple alternative thread wrapper class that allows setting a thread stack size, always calls <em>Execute</em> method and does not contain synchronization methods; it is well suited for console applications.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/582/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/582/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/582/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=582&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2011/12/18/tthread-facts/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>
	</item>
		<item>
		<title>Yet Another Word about FreeAndNil</title>
		<link>http://sergworks.wordpress.com/2011/12/14/yet-another-word-about-freeandnil/</link>
		<comments>http://sergworks.wordpress.com/2011/12/14/yet-another-word-about-freeandnil/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 08:16:45 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[FreeAndNil]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=578</guid>
		<description><![CDATA[The FreeAndNil discussion never stops. I decided to add my twopence. How about this: With FreeObj procedure you can have both “defensive coding” for debugging and clean production code. It is also clear that FreeAndNil is used just for debugging, so future maintainers will not be mislead and distracted by FreeAndNil usage. Since FreeObj is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=578&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The <em>FreeAndNil</em> discussion <a href="http://www.nickhodges.com/post/Using-FreeAndNil.aspx">never stops</a>. I decided to add my twopence. How about this:</p>
<p><pre class="brush: delphi;">
{.$DEFINE FREEANDNIL}
{$IFDEF FREEANDNIL}
procedure FreeObj(var Obj); inline;
begin
  FreeAndNil(Obj);
end;
{$ELSE}
procedure FreeObj(Obj: TObject); inline;
begin
  Obj.Free;
end;
{$ENDIF}
</pre></p>
<p>With <em>FreeObj</em> procedure you can have both “defensive coding” for debugging and clean production code. It is also clear that <em>FreeAndNil</em> is used just for debugging, so future maintainers will not be mislead and distracted by <em>FreeAndNil</em> usage.  Since <em>FreeObj</em> is inlined, it does not also have an influence on the executable code size.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/578/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/578/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/578/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=578&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2011/12/14/yet-another-word-about-freeandnil/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>
	</item>
		<item>
		<title>Hierarchical database structures and Firebird PSQL</title>
		<link>http://sergworks.wordpress.com/2011/12/09/hierarchical-database-structures-and-firebird-psql/</link>
		<comments>http://sergworks.wordpress.com/2011/12/09/hierarchical-database-structures-and-firebird-psql/#comments</comments>
		<pubDate>Fri, 09 Dec 2011 13:34:37 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Firebird]]></category>
		<category><![CDATA[ISQL]]></category>
		<category><![CDATA[PSQL]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=566</guid>
		<description><![CDATA[The idea of storing a hierarchical data in a relational database is very simple, but effective work with such a data requires some knowledge of server-side programming using procedural SQL (PSQL). So the hierarchical data structures are a good chance to get acquainted with PSQL. For demonstration purposes I created a simple database with single [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=566&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The idea of storing a hierarchical data in a relational database is very simple, but effective work with such a data requires some knowledge of server-side programming using procedural SQL (PSQL). So the hierarchical data structures are a good chance to get acquainted with PSQL. For demonstration purposes I created a simple database with single table TCLASS containing Delphi class hierarchy. Here is a SQL script that creates an empty database (I used Firebird version 2.1.4 and Firebird ISQL Tool to execute SQL scripts and single SQL statements):</p>
<p><pre class="brush: sql;">
SET SQL DIALECT 3;
SET NAMES WIN1251;
CREATE DATABASE 'localhost:c:\Projects\Hierarch\Test.FDB' user 'SYSDBA' password 'masterkey'
  DEFAULT CHARACTER SET UTF8;

COMMIT;

CREATE TABLE TCLASS (
  TCLASS_ID INTEGER NOT NULL,
  TCLASS_ANCESTOR_ID INTEGER,
  TCLASS_NAME VARCHAR(64) NOT NULL UNIQUE,
  CONSTRAINT PK_TCLASS
    PRIMARY KEY (TCLASS_ID)
  );

COMMIT;

CREATE GENERATOR GEN_TCLASS_ID;

SET TERM ^ ;

CREATE TRIGGER BI_TCLASS FOR TCLASS
ACTIVE BEFORE INSERT POSITION 0
AS
  BEGIN
    IF (NEW.TCLASS_ID IS NULL) THEN
      NEW.TCLASS_ID = GEN_ID(GEN_TCLASS_ID, 1);
  END^


CREATE PROCEDURE ADDCLASS(CLASS_NAME VARCHAR(64), ANCESTOR_NAME VARCHAR(64))
  RETURNS (CLASS_ID INTEGER)
AS
  DECLARE ANCESTOR_ID INTEGER;
  BEGIN
    CLASS_ID = 0;
    IF (ANCESTOR_NAME = '') THEN BEGIN
      CLASS_ID = GEN_ID(GEN_TCLASS_ID, 1);
      INSERT INTO TCLASS(TCLASS_ID, TCLASS_NAME)
        VALUES(:CLASS_ID, :CLASS_NAME);
    END
    ELSE BEGIN
      FOR
        SELECT TCLASS_ID
          FROM TCLASS
          WHERE TCLASS_NAME = :ANCESTOR_NAME
        INTO :ANCESTOR_ID
      DO BEGIN
        CLASS_ID = GEN_ID(GEN_TCLASS_ID, 1);
        INSERT INTO TCLASS(TCLASS_ID, TCLASS_ANCESTOR_ID, TCLASS_NAME)
          VALUES(:CLASS_ID, :ANCESTOR_ID, :CLASS_NAME);
      END
    END
  END^

CREATE PROCEDURE GETANCESTORS_EX(CURRENT_ID INTEGER, CURRENT_LEVEL INTEGER)
  RETURNS (CLASS_ID INTEGER, ANCESTOR_ID INTEGER, CLASS_NAME VARCHAR(64), CLASS_LEVEL INTEGER)
AS
  BEGIN
    FOR
      SELECT TCLASS_ID, TCLASS_ANCESTOR_ID, TCLASS_NAME
        FROM TCLASS
        WHERE TCLASS_ID = :CURRENT_ID
        INTO :CLASS_ID, :ANCESTOR_ID, :CLASS_NAME
    DO BEGIN
      CLASS_LEVEL = CURRENT_LEVEL - 1;
      SUSPEND;
      FOR
        SELECT CLASS_ID, ANCESTOR_ID, CLASS_NAME, CLASS_LEVEL
          FROM GETANCESTORS_EX(:ANCESTOR_ID, :CLASS_LEVEL)
          INTO :CLASS_ID, :ANCESTOR_ID, :CLASS_NAME, :CLASS_LEVEL
      DO BEGIN
        SUSPEND;
      END
    END
  END^

CREATE PROCEDURE GETANCESTORS(ID INTEGER)
  RETURNS (CLASS_ID INTEGER, CLASS_NAME VARCHAR(64), CLASS_LEVEL INTEGER)
AS
  BEGIN
    FOR
      SELECT TCLASS_ANCESTOR_ID
        FROM TCLASS
        WHERE TCLASS_ID = :ID
        INTO :CLASS_ID
    DO BEGIN
      CLASS_LEVEL = 1000;
      FOR
        SELECT CLASS_ID, CLASS_NAME, CLASS_LEVEL
          FROM GETANCESTORS_EX(:CLASS_ID, :CLASS_LEVEL)
          INTO :CLASS_ID, :CLASS_NAME, :CLASS_LEVEL
      DO BEGIN
        SUSPEND;
      END
    END
  END^

SET TERM ; ^

COMMIT;
</pre></p>
<p>TCLASS table contains TCLASS_ANCESTOR_ID field that links each record (Delphi class) with its ancestor record, so that TCLASS table can store a class hierarchy of unlimited depth:</p>
<p><pre class="brush: sql;">
CREATE TABLE TCLASS (
  TCLASS_ID INTEGER NOT NULL,
  TCLASS_ANCESTOR_ID INTEGER,
  TCLASS_NAME VARCHAR(64) NOT NULL UNIQUE,
  CONSTRAINT PK_TCLASS
    PRIMARY KEY (TCLASS_ID)
  );
</pre></p>
<p>Let us fill TCLASS table with data. To simplify the task I have written ADDCLASS procedure that inserts a single record into TCLASS table. The procedure has two parameters – a class name and ancestor class name. An ancestor class name is used to find an ancestor record ID.</p>
<p><pre class="brush: sql;">
CREATE PROCEDURE ADDCLASS(CLASS_NAME VARCHAR(64), ANCESTOR_NAME VARCHAR(64))
  RETURNS (CLASS_ID INTEGER)
AS
  DECLARE ANCESTOR_ID INTEGER;
  BEGIN
    CLASS_ID = 0;
    IF (ANCESTOR_NAME = '') THEN BEGIN
      CLASS_ID = GEN_ID(GEN_TCLASS_ID, 1);
      INSERT INTO TCLASS(TCLASS_ID, TCLASS_NAME)
        VALUES(:CLASS_ID, :CLASS_NAME);
    END
    ELSE BEGIN
      FOR
        SELECT TCLASS_ID
          FROM TCLASS
          WHERE TCLASS_NAME = :ANCESTOR_NAME
        INTO :ANCESTOR_ID
      DO BEGIN
        CLASS_ID = GEN_ID(GEN_TCLASS_ID, 1);
        INSERT INTO TCLASS(TCLASS_ID, TCLASS_ANCESTOR_ID, TCLASS_NAME)
          VALUES(:CLASS_ID, :ANCESTOR_ID, :CLASS_NAME);
      END
    END
  END^
</pre></p>
<p>If the second argument (ANCESTOR_NAME) is empty, the procedure assumes that the first argument (CLASS_NAME) is a name of the root of hierarchy (that should be <em>TObject</em> in Delphi); the procedure generates unique ID for a new record (TCLASS_ID field), leaves TCLASS_ANCESTOR_ID field empty (NULL) and executes INSERT SQL statement.<br />
If the second argument is not empty, we have ‘FOR SELECT &#8230; DO &#8230;’ construction. The procedure executes SELECT statement, and executes a block of code after ‘DO’ keyword for every row in a dataset created by SELECT statement. In our case the dataset contains only one record (it can also be empty if ANCESTOR_NAME argument is wrong – in this case no new record is inserted and the returned value of CLASS_ID is 0).<br />
Note that when a procedure parameters or local variables are used inside SQL statement (SELECT or INSERT) they should be preceded by ‘:’.<br />
Now we can fill TCLASS table with some data using ADDCLASS procedure; here is a simple SQL script:</p>
<p><pre class="brush: sql;">
CONNECT 'localhost:c:\Projects\Hierarch\Test.FDB' user 'SYSDBA' password 'masterkey';

EXECUTE PROCEDURE ADDCLASS('TObject','');
EXECUTE PROCEDURE ADDCLASS('TList','TObject');
EXECUTE PROCEDURE ADDCLASS('TPersistent','TObject');
EXECUTE PROCEDURE ADDCLASS('TCollection','TPersistent');
EXECUTE PROCEDURE ADDCLASS('TStrings','TPersistent');
EXECUTE PROCEDURE ADDCLASS('TStringList','TStrings');
EXECUTE PROCEDURE ADDCLASS('TStream','TObject');
EXECUTE PROCEDURE ADDCLASS('THandleStream','TStream');
EXECUTE PROCEDURE ADDCLASS('TFileStream','THandleStream');
COMMIT;
</pre></p>
<p>After executing the script TCLASS table contains the following data:</p>
<p><pre class="brush: plain;">
SQL&gt; SELECT * FROM TCLASS;
   TCLASS_ID  TCLASS_ANCESTOR_ID  TCLASS_NAME
================================================== 
           1             &lt;null&gt;   TObject 
           2                  1   TList 
           3                  1   TPersistent 
           4                  3   TCollection 
           5                  3   TStrings 
           6                  5   TStringList 
           7                  1   TStream 
           8                  7   THandleStream 
           9                  8   TFileStream 
SQL&gt;
</pre></p>
<p>A more interesting problem is to find all ancestors of a given class. The database contains two procedures that solve the problem. The first is</p>
<p><pre class="brush: sql;">
CREATE PROCEDURE GETANCESTORS_EX(CURRENT_ID INTEGER, CURRENT_LEVEL INTEGER)
  RETURNS (CLASS_ID INTEGER, ANCESTOR_ID INTEGER, CLASS_NAME VARCHAR(64), CLASS_LEVEL INTEGER)
AS
  BEGIN
    FOR
      SELECT TCLASS_ID, TCLASS_ANCESTOR_ID, TCLASS_NAME
        FROM TCLASS
        WHERE TCLASS_ID = :CURRENT_ID
        INTO :CLASS_ID, :ANCESTOR_ID, :CLASS_NAME
    DO BEGIN
      CLASS_LEVEL = CURRENT_LEVEL - 1;
      SUSPEND;
      FOR
        SELECT CLASS_ID, ANCESTOR_ID, CLASS_NAME, CLASS_LEVEL
          FROM GETANCESTORS_EX(:ANCESTOR_ID, :CLASS_LEVEL)
          INTO :CLASS_ID, :ANCESTOR_ID, :CLASS_NAME, :CLASS_LEVEL
      DO BEGIN
        SUSPEND;
      END
    END
  END^
</pre></p>
<p>The first parameter (CURRENT_ID) is an ID of the direct ancestor of a given class. The second parameter (CURRENT_LEVEL) can be any integer value; it’s only purpose is an option to sort the resulting dataset by ancestors’ level.<br />
The procedure is recursive. It has the same FOR SELECT &#8230; DO &#8230; logic as ADDCLASS procedure, but it uses SUSPEND statement in the block of code after DO keyword.<br />
The usage of SUSPEND statement means that the procedure is written to be called by SELECT statement, as different from ADDCLASS procedure that is written to be called by EXECUTE PROCEDURE statement. The SUSPEND statement passes a row of data to the outer SELECT statement, forming a resulting dataset. Here is a usage example:</p>
<p><pre class="brush: plain;">
SQL&gt; SELECT * FROM GETANCESTORS_EX(8, 99)
CON&gt; ORDER BY CLASS_LEVEL;
    CLASS_ID  ANCESTOR_ID CLASS_NAME     CLASS_LEVEL 
====================================================
           1       &lt;null&gt; TObject        96 
           7            1 TStream        97 
           8            7 THandleStream  98 

SQL&gt;
</pre></p>
<p>The first parameter value (8) is an ID of TFileStream direct ancestor (THandleStream), so the above SQL statement creates a dataset of TFileStream ancestors.<br />
The GETANCESTORS procedure does the same work as GETANCESTORS_EX procedure, but is more user-friendly; GETANCESTORS has the only parameter that is a given class ID (not an ancestor ID as with GETANCESTORS_EX procedure).</p>
<p><pre class="brush: sql;">
CREATE PROCEDURE GETANCESTORS(ID INTEGER)
  RETURNS (CLASS_ID INTEGER, CLASS_NAME VARCHAR(64), CLASS_LEVEL INTEGER)
AS
  BEGIN
    FOR
      SELECT TCLASS_ANCESTOR_ID
        FROM TCLASS
        WHERE TCLASS_ID = :ID
        INTO :CLASS_ID
    DO BEGIN
      CLASS_LEVEL = 1000;
      FOR
        SELECT CLASS_ID, CLASS_NAME, CLASS_LEVEL
          FROM GETANCESTORS_EX(:CLASS_ID, :CLASS_LEVEL)
          INTO :CLASS_ID, :CLASS_NAME, :CLASS_LEVEL
      DO BEGIN
        SUSPEND;
      END
    END
  END^
</pre></p>
<p>The usage example (9 is an ID of TFileStream):</p>
<p><pre class="brush: plain;">
SQL&gt; SELECT CLASS_ID INTEGER, CLASS_NAME
CON&gt; FROM GETANCESTORS(9)
CON&gt; ORDER BY CLASS_LEVEL;
   CLASS_ID CLASS_NAME
==========================
          1 TObject
          7 TStream
          8 THandleStream
SQL&gt;
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/566/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/566/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/566/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=566&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2011/12/09/hierarchical-database-structures-and-firebird-psql/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>
	</item>
		<item>
		<title>Why we need interfaces in Delphi.</title>
		<link>http://sergworks.wordpress.com/2011/12/08/why-we-need-interfaces-in-delphi/</link>
		<comments>http://sergworks.wordpress.com/2011/12/08/why-we-need-interfaces-in-delphi/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 15:45:01 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Interfaces]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=554</guid>
		<description><![CDATA[Objects are normally accessed by an object reference. Interface reference is a different method to access an object&#8217;s functionality. A simple question &#8211; why do we need interface references at all, why can’t we use object references everywhere? There are several reasons to use interface references instead of object references, but most important of them [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=554&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Objects are normally accessed by an object reference. Interface reference is a different method to access an object&#8217;s functionality. A simple question &#8211; why do we need interface references at all, why can’t we use object references everywhere?<br />
There are several reasons to use interface references instead of object references, but most important of them (at least historically) is accessing an object created in a different program module.<br />
Let us consider a simple example &#8211; an object is created in .dll module and consumed in .exe module.<br />
The <em>TMathObject</em> class implements <em>Square</em> and <em>Cube</em> functions on the <em>FOperand</em> field; we start with the following naive code:</p>
<p><pre class="brush: delphi;">
unit MathUnit;

interface

type
  TMathObject = class
  private
    FOperand: Double;
  public
    function Square: Double;
    function Cube: Double;
    property Operand: Double read FOperand write FOperand;
  end;

implementation

function TMathObject.Square: Double;
begin
  Result:= Sqr(FOperand);
end;

function TMathObject.Cube: Double;
begin
  Result:= Sqr(FOperand) * FOperand;
end;

end.
</pre></p>
<p>We want to create and destroy <em>TMathObject</em> instances in dll module:</p>
<p><pre class="brush: delphi;">
library MathDll;

uses
  MathUnit in 'MathUnit.pas';

function CreateObject: TMathObject;
begin
  Result:= TMathObject.Create;
end;

procedure FreeObject(Obj: TMathObject);
begin
  Obj.Free;
end;

exports
  CreateObject, FreeObject;

{$R *.res}

begin
end.
</pre></p>
<p>and use an instance of <em>TMathObject</em> in exe module:</p>
<p><pre class="brush: delphi;">
program MathTest;

{$APPTYPE CONSOLE}

uses
  MathUnit in 'MathUnit.pas';

function CreateObject: TMathObject; external 'MathDll.dll';
procedure FreeObject(Obj: TMathObject); external 'MathDll.dll';

var
  MathObj: TMathObject;

begin
  MathObj:= CreateObject;
  MathObj.Operand:= 2;
  Writeln('Square = ', MathObj.Square:3:2, '; Cube = ', MathObj.Cube:3:2);
  FreeObject(MathObj);
  Write('Press ''Enter'' key ... ');
  Readln;
end.
</pre></p>
<p>If you compile the above example you can see it works, but <em>TMathObject</em> implementation (MathUnit.pas) is duplicated in both program modules (MathTest.exe and MathDll.dll), and that is not just a waste of program memory.<br />
One of the main reasons to split a program into program modules is a possibility to modify the modules separately; for example to modify and deploy a different .dll version while keeping an .exe module intact. In the above example the implementation of <em>TMathObject</em> is a contract that both sides (exe and dll) should adhere, so the implementation of <em>TMathObject</em> can’t be changed in dll module only.<br />
We need a different form of contract that does not include an object&#8217;s implementation. A possible solution is to introduce a base class containing virtual abstract methods only:</p>
<p><pre class="brush: delphi;">
unit BaseMath;

interface

type
  TBaseMathObject = class
  protected
    function GetOperand: Double; virtual; abstract;
    procedure SetOperand(const Value: Double); virtual; abstract;
  public
    function Square: Double; virtual; abstract;
    function Cube: Double; virtual; abstract;
    property Operand: Double read GetOperand write SetOperand;
  end;

implementation

end.
</pre></p>
<p>Note that we can&#8217;t access <em>FOperand</em> field directly now because it is a part of <em>TMathObject</em> implementation that should be hidden in .dll module, so we introduce getter (<em>GetOperand</em>) and setter (<em>SetOperand</em>) virtual methods.<br />
Now we inherit a class that implements virtual methods from <em>TBaseMathObject</em>.</p>
<p><pre class="brush: delphi;">
unit MathUnit;

interface

uses BaseMath;

type
  TMathObject = class(TBaseMathObject)
  private
    FOperand: Double;
  protected
    function GetOperand: Double; override;
    procedure SetOperand(const Value: Double); override;
  public
    function Square: Double; override;
    function Cube: Double; override;
  end;

implementation

function TMathObject.GetOperand: Double;
begin
  Result:= FOperand;
end;

procedure TMathObject.SetOperand(const Value: Double);
begin
  FOperand:= Value;
end;

function TMathObject.Square: Double;
begin
  Result:= Sqr(FOperand);
end;

function TMathObject.Cube: Double;
begin
  Result:= Sqr(FOperand) * FOperand;
end;

end.
</pre></p>
<p>The library module source code now is</p>
<p><pre class="brush: delphi;">
library MathDll;

uses
  BaseMath in 'BaseMath.pas',
  MathUnit in 'MathUnit.pas';

function CreateObject: TBaseMathObject;
begin
  Result:= TMathObject.Create;
end;

procedure FreeObject(Obj: TBaseMathObject);
begin
  Obj.Free;
end;

exports
  CreateObject, FreeObject;

{$R *.res}

begin
end.
</pre></p>
<p>The executable module source code is</p>
<p><pre class="brush: delphi;">
program MathTest;

{$APPTYPE CONSOLE}

uses
  BaseMath in 'BaseMath.pas';

function CreateObject: TBaseMathObject; external 'MathDll.dll';
procedure FreeObject(Obj: TBaseMathObject); external 'MathDll.dll';

var
  MathObj: TBaseMathObject;

begin
  MathObj:= CreateObject;
  MathObj.Operand:= 2;
  Writeln('Square = ', MathObj.Square:3:2, '; Cube = ', MathObj.Cube:3:2);
  FreeObject(MathObj);
  Write('Press ''Enter'' key ... ');
  Readln;
end.
</pre></p>
<p>We can see that MathTest project does not contain MathUnit.pas unit, and is not dependent on <em>TMathObject</em> implementation; in fact MathTest project does not know that <em>TMathObject</em> class even exist. We can change <em>TMathObject</em> implementation in dll module as much as we want provided that we keep <em>TBaseMathObject</em> intact, inherit <em>TMathObject</em> from <em>TBaseMathObject</em> and override <em>TBaseMathObject</em>&#8216;s virtual abstract methods.<br />
We implemented a general concept of interface in the form of pure abstract class. Pure abstract classes are a way how interfaces are implemented in C++ . This approach has a limited value in Delphi because Delphi does not support multiple inheritance, and a Delphi class can have only one contract in the form of base abstract class. Another problem is a limited use of &#8216;is&#8217; and &#8216;as&#8217; operators for an object created in a different program module:</p>
<p><pre class="brush: delphi;">
program IsTest;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  BaseMath in 'BaseMath.pas';

function CreateObject: TBaseMathObject; external 'MathDll.dll';
procedure FreeObject(Obj: TBaseMathObject); external 'MathDll.dll';

var
  MathObj: TBaseMathObject;

procedure TestObj(Obj: TObject);
begin
  try
    Assert(Obj is TBaseMathObject);  // fails
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end;

procedure TestObj2(Obj: TBaseMathObject);
begin
  try
    Assert(Obj is TBaseMathObject);  // success
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end;

begin
  MathObj:= CreateObject;
  TestObj(MathObj);
  TestObj2(MathObj);
  FreeObject(MathObj);
  Write('Press ''Enter'' key ... ');
  Readln;
end.
</pre></p>
<p>Here is a brief explanation why the first assertion fails while the second assertion succeeds. Delphi class can be identified by its name or by its VMT. Even if a class does not define any virtual method and VMT itself is empty a pointer to class VMT is still valid. For the <em>TBaseMathObject</em> class we have a single name and two VMT&#8217;s, one in .exe module and one in .dll module. That may cause strange behavior, as shown in the above example.<br />
Starting from version 3 Delphi introduces a concept of interface that is different from a pure abstract class and solves the problems with object&#8217;s export by using interface references instead of object references:</p>
<p><pre class="brush: delphi;">
unit BaseMath;

interface

type
  IBaseMath = interface
  ['{92E9AFF4-25B7-41BD-9EB6-557D12F98BE6}']
    function GetOperand: Double;
    procedure SetOperand(const Value: Double);
    function Square: Double;
    function Cube: Double;
    property Operand: Double read GetOperand write SetOperand;
  end;

implementation

end.
</pre></p>
<p>There is no need to inherit <em>TMathObject</em> class from a given base class now; we can inherit <em>TMathObject</em> class from any class we like. Since all Delphi interfaces are descendants of <em>IUnknown</em> (also nicknamed as <em>IInterface</em> in Delphi) we should also implement the methods of <em>IUnknown</em> interface in <em>TMathObject</em> class. Delphi provides a helper <em>TInterfacedObject</em> class that already implements the methods of <em>IUnknown</em> and can be used as <em>TMathObject</em> ancestor:</p>
<p><pre class="brush: delphi;">
unit MathUnit;

interface

uses BaseMath;

type
  TMathObject = class(TInterfacedObject, IBaseMath)
  private
    FOperand: Double;
  protected
    function GetOperand: Double;
    procedure SetOperand(const Value: Double);
  public
    function Square: Double;
    function Cube: Double;
  end;

implementation

function TMathObject.GetOperand: Double;
begin
  Result:= FOperand;
end;

procedure TMathObject.SetOperand(const Value: Double);
begin
  FOperand:= Value;
end;

function TMathObject.Square: Double;
begin
  Result:= Sqr(FOperand);
end;

function TMathObject.Cube: Double;
begin
  Result:= Sqr(FOperand) * FOperand;
end;

end.
</pre></p>
<p>There is no need for <em>FreeObject</em> procedure now. The <em>FreeObject</em> procedure was introduced in the previous examples to enforce that a <em>TMathObject</em> instance is destroyed in the same program module where it was created (i.e. in .dll module). It is always a good rule of thumb that the one who creates an object is the one who destroys it. But now there is no need to enforce it &#8211; if we use interface references object instances are automatically destroyed in the same program module where they were created.</p>
<p><pre class="brush: delphi;">
library MathDll;

uses
  BaseMath in 'BaseMath.pas',
  MathUnit in 'MathUnit.pas';

function CreateObject: IBaseMath;
begin
  Result:= TMathObject.Create;
end;

exports
  CreateObject;

{$R *.res}

begin
end.
</pre></p>
<p>In the next example a <em>TMathObject</em> object instance is destroyed by assigning <em>nil</em> value to <em>MathObj</em> interface reference. In most cases there is no need for doing it because an object is destroyed automatically when all interface references goes out of scope. In the following code the <em>MathObj</em> interface reference is a global variable and never goes out of scope, so assigning it to <em>nil</em> explicitly makes sense:</p>
<p><pre class="brush: delphi;">
program MathTest;

{$APPTYPE CONSOLE}

uses
  BaseMath in 'BaseMath.pas';

function CreateObject: IBaseMath; external 'MathDll.dll';

var
  MathObj: IBaseMath;

begin
  MathObj:= CreateObject;
  MathObj.Operand:= 2;
  Writeln('Square = ', MathObj.Square:3:2, '; Cube = ', MathObj.Cube:3:2);
  MathObj:= nil;
  Write('Press ''Enter'' key ... ');
  Readln;
end.
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/554/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/554/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/554/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=554&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2011/12/08/why-we-need-interfaces-in-delphi/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>
	</item>
		<item>
		<title>Semaphore throttle</title>
		<link>http://sergworks.wordpress.com/2011/12/08/semaphore-throttle/</link>
		<comments>http://sergworks.wordpress.com/2011/12/08/semaphore-throttle/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 07:06:22 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Semaphore]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=543</guid>
		<description><![CDATA[Suppose we have an algorithm that uses N parallel threads, and we have a system with M CPU cores, N &#62; M. Running the algorithm on the system leads to performance loss because the threads are contend for available CPU cores and cause time-consuming thread context switching. A better approach is to execute threads sequentially [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=543&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Suppose we have an algorithm that uses N parallel threads, and we have a system with M CPU cores, N &gt; M. Running the algorithm on the system leads to performance loss because the threads are contend for available CPU cores and cause time-consuming thread context switching. A better approach is to execute threads sequentially on the available CPU cores, to avoid the unnecessary thread context switching. There is a simple technique called <strong><em>semaphore throttle</em></strong> which limits the number of active, contending threads.<br />
It is interesting to estimate how efficient semaphore throttle is on real system. Or, in other words, how much is the performance loss caused by thread context switching.<br />
As a test problem I have chosen the sum of arithmetic progression: <em>S = 1 + 2 + 3 +&#8230; + Count * 64</em> . To find the sum I run 64 threads, each thread calculates a partial sum from <em>1 + I * Count</em> to <em>(I + 1) * Count, I = [0..63]</em>.<br />
To obtain valid timings it is important that each thread is executed sufficiently long, so that the thread is preempted many times by other contending threads (when the scheduler&#8217;s time quantum ends). To increase the thread execution time I turned optimization off and chosen the Count value as much as possible for the resulting sum to fit into int64 range, but it appeared insufficient. Finally I decided to insert an additional loop into the thread function so that the thread execution time exceeded 1 second on my system:</p>
<p><pre class="brush: delphi;">
unit SumThreads;

interface

uses
  Windows, Classes;

type
  TSumThread = class(TThread)
  private
    FSum: Int64;
    FBase: Integer;
    FCount: Integer;
    FSemaphore: THandle;
  protected
    procedure Execute; override;
  public
    constructor Create(ABase, ACount: Integer; ASemaphore: THandle);
    property Sum: Int64 read FSum;
  end;

implementation

{$O-}

constructor TSumThread.Create(ABase, ACount: Integer; ASemaphore: THandle);
begin
  FBase:= ABase;
  FCount:= ACount;
  FSemaphore:= ASemaphore;
  inherited Create(False);
end;

procedure TSumThread.Execute;
var
  Cnt, Value, J: Integer;
  S: Int64;

begin
  if FSemaphore &lt;&gt; 0 then
    WaitForSingleObject(FSemaphore, INFINITE);
  try
// to increase execution time the calculation is repeated
    J:= 20;
    repeat
      Value:= FBase;
      Cnt:= FCount;
      S:= 0;
      repeat
        S:= S + Value;
        Inc(Value);
        Dec(Cnt);
      until Cnt = 0;
      FSum:= S;
      Dec(J);
    until J = 0;
  finally
    if FSemaphore &lt;&gt; 0 then
      ReleaseSemaphore(FSemaphore, 1, nil);
  end;
end;

end.
</pre></p>
<p>To run the test I have written a simple console application that receives the number of concurrent threads as command line parameter, and outputs the number of concurrent threads and total execution time in seconds:</p>
<p><pre class="brush: delphi;">
program throttle;

{$APPTYPE CONSOLE}

uses
  Windows,
  SysUtils,
  Classes,
  Diagnostics,
  SumThreads in 'SumThreads.pas';

const
  CHUNK = 30000000;

var
  Semaphore: THandle;
  Count, I: Integer;
  Sum: Int64;
  Threads: array[0..63] of TSumThread;
  Handles: array[0..63] of THandle;
  StopWatch: TStopWatch;

begin
  try
    if ParamCount &lt;&gt; 1 then
      raise Exception.Create('Number of concurrent threads not defined');
    Count:= StrToInt(ParamStr(1));
    if (Count &lt; 0) or (Count &gt; 64) then
      raise Exception.Create('Invalid number of concurrent threads');
    if Count &lt;&gt; 0 then begin
      Semaphore:= CreateSemaphore(nil, Count, Count, nil);
      Win32Check(Bool(Semaphore));
    end
    else
      Semaphore:= 0;
    try
      StopWatch:= TStopWatch.StartNew;
      for I:= 0 to 63 do begin
        Threads[I]:= TSumThread.Create(1 + I * CHUNK, CHUNK, Semaphore);
        Handles[I]:= Threads[I].Handle;
      end;
      if WaitForMultipleObjects(64, @Handles, True, INFINITE) = WAIT_FAILED
        then raise Exception.Create('WaitForMultipleObjects Failed');
      StopWatch.Stop;
      Sum:= 0;
      for I:= 0 to 63 do begin
        Sum:= Sum + Threads[I].Sum;
        Threads[I].Free;
      end;
    finally
      CloseHandle(Semaphore);
    end;
    Writeln(Count:5, ' -- ', StopWatch.Elapsed.TotalSeconds:3:2);
//    Writeln('Number of concurrent threads: ', Count);
//    Writeln('Time elapsed (seconds): ', StopWatch.Elapsed.TotalSeconds:3:2);
//    Writeln('Sum obtained: ', Sum);
//    Sum:= CHUNK * 64; // number of summands
//    Sum:= (Sum * (Sum + 1)) div 2;
//    Writeln('Sum expected: ', Sum);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
</pre></p>
<p>I ran the tests on my notebook with 64-bit Windows 7 SP1 and CPU Intel Core i3 M380 using a simple batch file <em>throttle.bat</em>:</p>
<p><pre class="brush: plain;">
@echo off
time /t
throttle 1
throttle 2
throttle 3
throttle 4
throttle 5
throttle 6
throttle 8
throttle 16
throttle 32
throttle 64
throttle 0
time /t
</pre></p>
<p>The resulting log is</p>
<p><pre class="brush: plain;">
13:17
    1 -- 109.17
    2 -- 55.44
    3 -- 60.14
    4 -- 67.56
    5 -- 67.85
    6 -- 67.42
    8 -- 67.39
   16 -- 67.52
   32 -- 67.56
   64 -- 67.59
    0 -- 67.55
13:30
</pre></p>
<p>It can be clearly seen that my CPU has 2 physical cores (the number of logical cores for Core i3 M380 is 4); the fastest execution time is achieved by allowing two threads to be executed concurrently. Running 3 concurrent threads is slower, running 4 concurrent threads is even more slow. But there is no further performance degradation.<br />
If you think of the results you can guess that if N concurrent threads are executed on M CPU cores the performance should degrade from N = M to N = 2M because of the increasing number of thread context switching (I have not tested it since I have no appropriate systems). For N &gt; 2M the number of thread context switching should not grow anymore &#8211; now we have at least 2 concurrent threads per each core, each thread is preempted when every scheduler&#8217;s timeslice ends, that is the &#8216;worst case&#8217; situation and it is reached at N = 2M.<br />
A little arithmetic shows that properly tuned semaphore throttle can give about 15-20% performance gain on my notebook. Different systems can show different results.</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>You can download tests (both source code and executable) <a title="Semaphore throttle tests" href="http://kstools.googlecode.com/files/throttle.zip">here</a></p>
<p>&nbsp;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/543/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/543/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/543/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=543&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2011/12/08/semaphore-throttle/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>
	</item>
		<item>
		<title>Dotted unit names in Delphi</title>
		<link>http://sergworks.wordpress.com/2011/08/09/dotted-unit-names-in-delphi/</link>
		<comments>http://sergworks.wordpress.com/2011/08/09/dotted-unit-names-in-delphi/#comments</comments>
		<pubDate>Tue, 09 Aug 2011 05:31:38 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Namespaces]]></category>
		<category><![CDATA[Pulsar]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=533</guid>
		<description><![CDATA[For some time now (probably since Delphi 2005; at least the feature is present in Delphi 2007) Delphi has support for dotted unit names (like myLib.myUtils.pas). A fully qualified unit name (myLib.myUtils.pas) consists of a scope prefix (myLib) and a scoped or partially qualified unit name (myUtils.pas). The compiler supports scope prefixes as can be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=533&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>For some time now (probably since Delphi 2005; at least the feature is present in Delphi 2007) Delphi has support for dotted unit names (like <em>myLib.myUtils.pas</em>). A fully qualified unit name (<em>myLib.myUtils.pas</em>) consists of a scope prefix (<em>myLib</em>) and a scoped or partially qualified unit name (<em>myUtils.pas</em>). The compiler supports scope prefixes as can be seen in Project/Options dialog (&#8216;Namespace prefixes&#8217;, Delphi 2009):<br />
<a href="http://sergworks.files.wordpress.com/2011/08/namespace2009.png"><img class="aligncenter size-full wp-image-534" title="Namespace2009" src="http://sergworks.files.wordpress.com/2011/08/namespace2009.png?w=720" alt=""   /></a><br />
If you add a scope prefix (<em>myLib</em>) to the list of Namespace prefixes of a project you can use a scoped unit name (<em>myUtils</em>) instead of a fully qualified unit name (<em>myLib.myUtils</em>).</p>
<p>Not much really. I would certanly prefer</p>
<p><pre class="brush: delphi;">
uses
  myLib.myUtils;
</pre></p>
<p>to messing about with project options just to write a scoped unit name</p>
<p><pre class="brush: delphi;">
uses
  myUtils;
</pre></p>
<p>Things are changing with Delphi XE2. I have not found any additional support for scope prefixes (only &#8216;Namespace prefixes&#8217; is renamed by &#8216;Unit Scope Names&#8217; in Project options dialog), but scope prefixes are extensively used. There are reasons for it.</p>
<p>Most generic unit names are now scoped unit names. For example, &#8216;<em>Classes.pas</em>&#8216; now belongs to &#8216;<em>System</em>&#8216; namespace and its fully qualified name is &#8216;<em>System.Classes.pas</em>&#8216;. For the new units using fully qualified names like this</p>
<p><pre class="brush: delphi;">
uses
  System.Classes;
</pre></p>
<p>is preferable, but to compile a project with a lot of legacy units (or to support previous Delphi versions) a better option is to add &#8216;System&#8217; prefix to &#8216;Unit Scope Names&#8217; in Project options dialog.</p>
<p>We now have two GUI application frameworks &#8211; VCL and FMX. Many unit names exist in both frameworks, for example <em>VCL.Dialogs.pas</em> and <em>FMX.Dialogs.pas</em>. It is possible to write a framework dependent unit that can be used with both frameworks.</p>
<p>As an example I have written a simple unit that uses Dialogs.pas:</p>
<p><pre class="brush: delphi;">
unit TestUnit;

interface

uses
  Dialogs;

procedure Test;

implementation

procedure Test;
begin
  ShowMessage('Hello World!');
end;

end.
</pre></p>
<p>I created a VCL Forms application and added a button to the main form:</p>
<p><pre class="brush: delphi;">
uses TestUnit;

{$R *.dfm}

procedure TForm17.Button1Click(Sender: TObject);
begin
  Test;
end;
</pre></p>
<p>The application was compiled without a hitch because &#8216;VCL&#8217; scope prefix is already added to project options in VCL application template.</p>
<p>Now I created a FMX Forms application with the same button, tried to build it and got a compile error:</p>
<p><pre class="brush: plain;">
[DCC Fatal Error] TestUnit.pas(6): F1026 File not found: 'Dialogs.dcu' (unit may not be available for the targeted platform)
</pre></p>
<p>It appeared that FMX application template does not add &#8216;FMX&#8217; scope prefix to the list of unit scope names. I don&#8217;t know is it done on purpose or it will change in final release.</p>
<p>So I added &#8216;FMX&#8217; scope prefix manually and got the application compiled, now with FMX implementation of <em>ShowMessage</em> (yes, it looks different from VCL&#8217;s one).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/533/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/533/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/533/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/533/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/533/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/533/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/533/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/533/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/533/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/533/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/533/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/533/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/533/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/533/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=533&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2011/08/09/dotted-unit-names-in-delphi/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>

		<media:content url="http://sergworks.files.wordpress.com/2011/08/namespace2009.png" medium="image">
			<media:title type="html">Namespace2009</media:title>
		</media:content>
	</item>
		<item>
		<title>Sleep sort and TThread corner case</title>
		<link>http://sergworks.wordpress.com/2011/06/25/sleep-sort-and-tthread-corner-case/</link>
		<comments>http://sergworks.wordpress.com/2011/06/25/sleep-sort-and-tthread-corner-case/#comments</comments>
		<pubDate>Sat, 25 Jun 2011 05:22:19 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Sleep sort]]></category>
		<category><![CDATA[Threads]]></category>
		<category><![CDATA[TThread]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=517</guid>
		<description><![CDATA[If you have not heard it yet &#8211; an anonymous genius from 4chan invented a sleep sort, brilliant esoteric sorting algorithm. I have written sleep sort implementation based on Delphi TThread class for rosettacode project, and started to experiment with the code. One of the working variants is: Now, if you look at TThread source [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=517&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you have not heard it yet &#8211; an anonymous genius from <a title="4chan" href="http://dis.4chan.org/read/prog/1295544154" target="_blank">4chan</a> invented <em>a sleep sort</em>, brilliant esoteric sorting algorithm. I have written sleep sort implementation based on Delphi TThread class for rosettacode project, and started to experiment with the code. One of the working variants is:</p>
<p><pre class="brush: delphi;">
program SleepSortDemo2;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, SyncObjs;

type
  TSleepThread = class(TThread)
  private
    FValue: Integer;
    FLock: TCriticalSection;
  protected
    constructor Create(AValue: Integer; ALock: TCriticalSection);
    procedure Execute; override;
  end;

const
  ArrLen = 16;

var
  A: array[0..ArrLen - 1] of Integer;
  Threads: array[0..ArrLen - 1] of TThread;
  Lock: TCriticalSection;
  I: Integer;

constructor TSleepThread.Create(AValue: Integer; ALock: TCriticalSection);
begin
  FValue:= AValue;
  FLock:= ALock;
  inherited Create(False);
end;

procedure TSleepThread.Execute;
begin
  Sleep(1000 * FValue);
  FLock.Acquire;
  Write(FValue:3);
  FLock.Release;
end;

begin
  for I:= 0 to ArrLen - 1 do begin
    A[I]:= Random(15);
    Write(A[I]:3);
  end;
  Writeln;

  Lock:= TCriticalSection.Create;
  for I:= 0 to ArrLen - 1 do
    Threads[I]:= TSleepThread.Create(A[I], Lock);
  for I:= 0 to ArrLen - 1 do begin
    Threads[I].WaitFor;
    Threads[I].Free;
  end;
  Lock.Free;

  Writeln;
  Readln;
end.
</pre></p>
<p>Now, if you look at TThread source code you can see that <em>TThread.WaitFor</em> is called from <em>TThread.Destroy</em>, so it seems that there is no need for a separate  <em>Threads[I].WaitFor</em> call and the line #53 can be commented. Try it, and the code does not work anymore (at least it does not work on the system I used for testing &#8211; Windows 7 SP1, Celeron 530 CPU, 2 Gb RAM).</p>
<p>After pondering at the problem for some time I understood that <em>TThread.Destroy</em> just does not wait for the thread to terminate. But why? Look at the code snippet from <em>TThread.Destroy</em>:</p>
<p><pre class="brush: delphi;">
  if (FThreadID &lt;&gt; 0) and not FFinished and not FExternalThread then
  begin
    Terminate;
    if FCreateSuspended then
      Resume;
    WaitFor;
  end;
</pre></p>
<p>All conditions are satisfied. You can set a breakpoint on <em>WaitFor</em> line and see that <em>WaitFor</em> method is actually called&#8230;</p>
<p>The answer was found in the <em>ThreadProc</em> function. Here is a code snippet from it:</p>
<p><pre class="brush: delphi;">
  ..
  try
    if not Thread.Terminated then
    try
      Thread.Execute;
    except
      Thread.FFatalException := AcquireExceptionObject;
    end;
  finally
  ..
</pre></p>
<p>See what happens? <em>TThread.Destroy</em> calls <em>Terminate</em> and sets <em>TThread.Terminated</em> flag. But the thread has not started yet. Now the thread starts, <em>ThreadProc</em> function checks <em>TThread.Terminated</em> flag, and the <em>Execute</em> method is never called!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/517/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/517/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/517/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=517&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2011/06/25/sleep-sort-and-tthread-corner-case/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>
	</item>
		<item>
		<title>Generic musings 2</title>
		<link>http://sergworks.wordpress.com/2011/05/11/generic-musings-2/</link>
		<comments>http://sergworks.wordpress.com/2011/05/11/generic-musings-2/#comments</comments>
		<pubDate>Wed, 11 May 2011 12:20:03 +0000</pubDate>
		<dc:creator>Serg</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Generics]]></category>

		<guid isPermaLink="false">http://sergworks.wordpress.com/?p=501</guid>
		<description><![CDATA[It was pointed out in the comments to my previous post that my simple generic sorting routine contains additional overhead compared to TArray Rtl code (Generic.Collections &#38; Generic.Defaults units) because RTTI is used inside the loop. Yes, that is true. Let us improve the code by taking RTTI check away from the loop, while keeping [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=501&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It was pointed out in the comments to my <a href="http://sergworks.wordpress.com/2011/05/10/generic-musings/">previous post</a> that my simple generic sorting routine contains additional overhead compared to TArray Rtl code (Generic.Collections &amp; Generic.Defaults units) because RTTI is used inside the loop. Yes, that is true. Let us improve the code by taking RTTI check away from the loop, while keeping the code simple (without using over-weighted and tricky IComparer interface).</p>
<p>Simple tasks should have simple solutions. Now when I look at it the solution seems quite obvious, still I spent some hours trying to find it – generics are weird for beginner. The last step that led to working code was to declare generic procedural type TCompare inside generic class TArray, without it the code would not compile:</p>
<p><pre class="brush: delphi;">
unit GenericSort;

interface

type
  TArray&lt;T&gt; = class
  public type
    TCompare = function(const L, R: T): Integer;
  private
    class procedure InternalSort(var A: array of T;
      Compare: TCompare); static;
  public
    class procedure InsertionSort(var A: array of T); static;
  end;

function CompareInt(const L, R: Integer): Integer;

implementation

uses SysUtils, TypInfo;

class procedure TArray.InternalSort(var A: array of T; Compare: TCompare);
var
  I, J: Integer;
  Item: T;
  P: PTypeInfo;

begin
  for I:= 1 + Low(A) to High(A) do begin
    Item:= A[I];
    J:= I - 1;
    while (J &gt;= Low(A)) and (Compare(A[J], Item) &gt; 0) do begin
      A[J + 1]:= A[J];
      Dec(J);
    end;
    A[J + 1]:= Item;
  end;
end;

function CompareInt(const L, R: Integer): Integer;
begin
 if L &lt; R then Result:= -1
  else if L &gt; R then Result:= 1
  else Result:= 0;
end;

class procedure TArray.InsertionSort(var A: array of T);
var
  P: PTypeInfo;

begin
  P:= TypeInfo(T);
  case P^.Kind of
    tkInteger: InternalSort(A, @CompareInt);
    tkUString: InternalSort(A, @CompareStr);
  end;
end;

end.
</pre></p>
<p>Note that the function &#8216;CompareInt&#8217; is declared in interface section. If you comment out interface declaration you get compile error</p>
<p><em>[DCC Error] GenericSort.pas(54): E2506 Method of parameterized type declared in interface section must not use local symbol &#8216;CompareInt&#8217;.<br />
</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sergworks.wordpress.com/501/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sergworks.wordpress.com/501/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sergworks.wordpress.com/501/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sergworks.wordpress.com/501/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sergworks.wordpress.com/501/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sergworks.wordpress.com/501/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sergworks.wordpress.com/501/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sergworks.wordpress.com/501/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sergworks.wordpress.com/501/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sergworks.wordpress.com/501/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sergworks.wordpress.com/501/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sergworks.wordpress.com/501/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sergworks.wordpress.com/501/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sergworks.wordpress.com/501/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sergworks.wordpress.com&amp;blog=10209046&amp;post=501&amp;subd=sergworks&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sergworks.wordpress.com/2011/05/11/generic-musings-2/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/665c722f073326deabf01c902f0bab45?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sergworks</media:title>
		</media:content>
	</item>
	</channel>
</rss>
