ReadLn / WriteLn problem (Please ignore other post)

Giganews Newsgroups
Subject: ReadLn / WriteLn problem (Please ignore other post)
Posted by:  m00bh000 (timkelly19…
Date: Fri, 9 Jun 2006


I have an Indy TCP/IP server & client implementation, both with the following execute loops, which send and receive
my custom packets:

OnExecute(AThread : TIDPeerThread)
var myCustomPacket : string;

  myCustomPacket := AThread.Connection.ReadLn(#$A, 100, -1);
  if myCustomPAcket <> EmptyStr then ProcessPacket(myCustomPacket);

  myCustomPacket := MyThreadSafeStringQueue.Pop; { Returns EmptyStr if queue empty, data is being pushed to this queue by different thread }
  if myCustomPacket <> emptyStr then AThread.Connection.WriteLn(myCustomPacket);

  while not AThread.Terminated do


This code works, but there is a problem:

Sometimes there are lots of packets to write and not many to be read. But the Write function is having to wait 100ms every time it wants to write.

I don't want to set the ReadLn timeout to 1ms because I think this will use too much CPU time.

MyThreadSafeStringQueue is essentially a buffer of stuff to be written, i didn't want the sending thread to be accesing the connection directly because:

    a) I wasn't sure if this you can saftly ReadLn and WriteLn from different threads at the same time
    b) The sending thread is doing some very important stuff and needs to be quick, so pushing the data 2 the queue is nice and quick.

I guess I could always have a 3rd thread for writing, but this still depends on ReadLn and WriteLn being safe.

Incidently MyThreadSafeStringQueue does have a TSimpleEvent which is signalled if there is data waiting to be sent. I thought about setting the ReadLn timeout to 1ms and then waiting on this event instead. But of course this just reverses the problem and introduces 100ms blocking on the reader. I suppose I could have 50ms delays on both but it's not ideal.

What would be great is if I could do something like:

WaitForMultipleEvents(Connection.DataWaitingEvent, SentQueue.DataWaitingEvent)

but don't know if there is such a possibilty.

Any ideas?!!