[Lazarus] lNet and several threads

AleŇ° Katona almindor at gmail.com
Sat Apr 18 10:53:39 CEST 2009


On Sat, 18 Apr 2009 10:36:04 +0200
User <usuarioanonimomysql at gmail.com> wrote:

> Hello, I will explain better my doubt. I need to program a multithread
> server that processes requests of several clients at the same time. At the
> moment the server processes requests of several clients one to one by the
> OnReceive callback:
> 
> procedure TConnectionHandler.Receive(aSocket: TLSocket);
> var
>   Message: String;
> begin
>   if aSocket.GetMessage(Message) > 0 then
>     MessagesManager.ProcessMessage(Message);
> end;
> 
> I want to change the behavior of the server so that it works with one thread
> for each client request.
> 
> Is it possible?
> 
> Best regards.
> 
> 2009/4/18 AleŇ° Katona <almindor at gmail.com>
> 
> > On Thu, 16 Apr 2009 20:01:57 +0200
> > User <usuarioanonimomysql at gmail.com> wrote:
> >
> > > How I can use several threads with lNet visual library?
> > >
> > > I need some examples.
> > >
> > > Best regards!
> >
> > Hello. lNet is inheritedly not thread-safe but it can be used with threads
> > in some ways. When it comes to the visual components, you must remember that
> > the main program loop (handled by the widgetsets) calls the lNet callbacks
> > (OnReceive etc.) so they are all executed inside the main thread no matter
> > where you work with the components otherwise.
> >
> > I'd need some specific use case to give more info.
> >
> > Ales
> > _______________________________________________
> > Lazarus mailing list
> > Lazarus at lazarus.freepascal.org
> > http://www.lazarus.freepascal.org/mailman/listinfo/lazarus
> >

Yes, but you need to do the sends inside the main loop. lNet is a state-machine so everything related to network states needs to be kept in the same thread. You can however start a new thread for each request and process the data there. When you have replies ready to send, push them in some send-buffer (per client) so that the main thread can do the sending then. This requires some sort of messaging between the threads of course.

It's not the simplest of methods but it's safe. Doing sending inside the work-threads could cause lNet to run into a state-change race-condition and stop working properly.

Ales




More information about the Lazarus mailing list