Newsgroups : Borland : borland.public.delphi.internet.winsock : 2006 Mar : Re: TIdTCPServer - threads, global data

www.cryer.info
Managed Newsgroup Archive

Re: TIdTCPServer - threads, global data

Subject:Re: TIdTCPServer - threads, global data
Posted by:"Remy Lebeau (TeamB)" (no.spam@no.spam.com)
Date:Thu, 16 Mar 2006 11:24:16

"Mathijs" <blabla@bla.hu> wrote in message
news:Xns9788B1D6A94AEholleknolle23@207.105.83.66...

> Thanks. This is new for me. Can I use(read/write) the objects
> stored in the TThreadList no matter what kind of object it is?

The TList inside of TThreadList is not directly accessible.  You have to
call the TThreadList's Lock() method in order to reach the TList.  Once
LockList() has returned, the thread can do whatever it wants with the TList
contents.  When the thread is done with the TList, it needs to call the
TThreadList's UnlockList() method so that another thread can then use the
TList.  When one thread calls LockList() while another thread already has
the list locked, the first thread is blocked until the second thread unlocks
the list.

This way, multiple threads cannot gain access to the TList at the same time.

> And what if I want to use a TStringList?

TThreadList is the only container in the VCL that is thread-safe as-is.
Indy, on the other hand, implements several thread-safe containers of its
own.  Look at the various classes in the IdThreadSafe unit, such as
TIdThreadSafeStringList.

> Or a TWhatEver? Put it in a TThreadList (threadlist.add(AWhatEver);)
> and use it from there (TWhatEver(threadlist.items[0]).DoSomething)?

Almost.  It would be more like this:

    begin
        // Add() calls (Un)LockList() internally
        ThreadList.Add(AWhatEver);
    end;

    var
        List: TList;
    begin
        List := ThreadList.LockList;
        try
            TWhatEver(List.Items[0]).DoSomething;
        finally
            ThreadList.UnlockList;
        end;
    end;


> Or is it better to make TWhatever thread safe from scratch
> (with a critical section)?

That is an alternative approach.


Gambit

Replies:

In response to:

www.cryer.info
Managed Newsgroup Archive