Reputation: 1658
I have to call a function in a anonymous thread in a while
my sample function is like this, just for print output:
function processPureTmFrame(rowFrame : string;tmDataGroupRef:string ):string;
TThread.Synchronize(nil,
procedure
begin
form2.Memo1.Lines.Add( tmSlitFrame );
end
);
end;
when i call the function like this :
code1
while tmBody.Length>0 do
begin
tmBodyFrameLength := ((hextodec( copy(tmBody,11,2) )+6)*2)+2;
tmSplitFrame := copy(tmBody , 1 , tmBodyFrameLength );
delete( tmBody, 1, tmBodyFrameLength );
myThread := TThread.CreateAnonymousThread(
procedure
begin
processPureTmFrame( tmSplitFrame , tmDataGroupRef );
end);
myThread.Start;
end;
in the first cycle of loop the output is missing
but when i call my code without thread every thing is ok!!
code2
while tmBody.Length>0 do
begin
tmBodyFrameLength := ((hextodec( copy(tmBody,11,2) )+6)*2)+2;
tmSplitFrame := copy(tmBody , 1 , tmBodyFrameLength );
delete( tmBody, 1, tmBodyFrameLength );
processPureTmFrame( tmSplitFrame , tmDataGroupRef );
end;
the correct output must be like this
0851C007000C010100000007581850C001F116
0836C0BE001003627169DCA200000000000090D72AACAF
0814C0B6001C03197169DCA31901E2041211131D001F00001F1E1C1F1F1E1E1E0077AA
0814C0B7001E03197169DCA31902FE00540F0000000000000000000000000000000000E238
0814C0B8000B03197169DCA31903FE01384E
0817C0B9000D05017169DCA3E6010190B03F042D
0852C000000B036200000000FAFFFFBF16A3
0852C001000B036200000001F4FF00000000
but when call in thread(code 1) its is like
0836C0BE001003627169DCA200000000000090D72AACAF
0814C0B6001C03197169DCA31901E2041211131D001F00001F1E1C1F1F1E1E1E0077AA
0814C0B7001E03197169DCA31902FE00540F0000000000000000000000000000000000E238
0814C0B8000B03197169DCA31903FE01384E
0817C0B9000D05017169DCA3E6010190B03F042D
0852C000000B036200000000FAFFFFBF16A3
0852C001000B036200000001F4FF00000000
without thread(code 2) output is ok
Note #1: I don't get any error like:
System Error. Code:1400. Invalid window handle or any thing else
Note #2: as I said just first cycle of while not sending to the new threads. Other lines are sending and processing just fine!
Upvotes: 1
Views: 2464
Reputation: 612954
The problem is that the anonymous method captures variables. Because the variable is captured, its value changes during the main loop. Essentially all the threads share the same variable. The threads run in parallel with the main loop and there are no ordering constraints. So it's perfectly possible that the main loop modifies the captured variable before one of your threads has a chance to use the value.
Your code would work with value capture (as opposed to variable capture). Value capture is not supported directly but the same effect is easy to simulate. See Anonymous methods - variable capture versus value capture.
I would comment though that this threading code is going to be slower than the serial code. What are you hoping to achieve?
Upvotes: 4