tags:

views:

138

answers:

2

Hello

Is this some kind of exception dead lock i am facing? How to avoid it ?

Have a look at below line where i have TIdContext objects of connected clients stored in an objlist and at times i need to process it. But if one user is disconnected while another thread is processing the list, then for that freed TIdContext->Data object I am getting Access voilation, Ok its fine i am using try/catch but problem is that at below line there is some kind of dead lock and process hangs , if i attach a debuger it show Access voilation Again and Again and Again, and cpu coonsumption goes up because of that exception dead lock.

AnsiString UserID = ((Tmyobject*) ((TIdContext*) ObjList->Objects[i])->Data)->UserID;

i know i can check before accessing the object, if object is not Null, It works.. But my question is what if once in a blue moon the Data object is freed at the point when NULL check is performed and on next line when again i am accessing the object i get same dead lock ???

So how to avoid/handle this dead lock exception ?

Here is the call stack...

:005F07C0 System::AnsiStringBase::AnsiStringBase(this=:0285FCE0, src=????)
:0040223F System::AnsiStringT<0>::AnsiStringT<0>(this=:0285FCE0, src=:00000008)
:00457996 TSomeClass::SomeFunction(this=:009D8230, UserID={  }, DataSize={  }, )
:0047BFF1 __linkproc__ ThreadProc(Thread=:009561C0)
:004AD00E __linkproc__ ThreadWrapper(Parameter=:009EAA30)
:7c80b729 ; C:\WINDOWS\system32\kernel32.dll

Please helppppppppppppppppppppp

Thanks

+2  A: 

Don't use try/catch to deal with access violations. These are not Java NullPointerExceptions, try/catch can not deal with the havoc they wreak. Fix the underlying bug instead.

A deadlock is when two or more threads get stuck forever, waiting for one another to do something. What you have is a race condition: one thread is updating the object list while the other is trying to use it, and if the first thread finishes too quickly it can inadvertently break the second thread.

The standard way to deal with a race condition is to put a lock of some kind around all the code that uses the contested resource, so that the threads using it politely take turns instead of racing with one another. Read up on mutexes: they're a simple synchronization primitive, but are probably powerful enough to solve your problem.

David Seiler
+1  A: 

The Contexts property of the TIdTCPServer is a thread-safe TThreadList so you should be able to use LockList/UnlockList to iterate through the active contexts without the server changing them in the meantime. If you're maintaining a separate list there are several options but you'll have to post a bit more code describing how you're adding to/removing from that list.

Peter Hull
Yes, do use the server's built-in client list, do not manage your own separately. They can easily get out of sync during connects/disconnects.
Remy Lebeau - TeamB