How to automatically initialize / uninitialize something globally for each thread?

I have a block with sections initialization and finalization . This block contains a complex object that is created in initialization and destroyed in finalization . However, this object also contains an ADO connection. This makes it a problem when using this in threads, since ADO is COM, and it needs to be initialized for each thread.

This is how I process this instance of the global object now:

 uses ActiveX; ... initialization CoInitialize(nil); _MyObject:= TMyObject.Create; finalization _MyObject.Free; CoUninitialize; end. 

This only works in the main thread. Any other thread will not be able to access it and will return a CoInitialize has not been called exception.

How do I get around this to make this block thread safe? I need a way to bind every creation / destruction of any created thread, and each thread will have to reference a different instance of this object. But how to do that?

+2
multithreading initialization delphi ado delphi-xe2
source share
2 answers

Well, as you said, each thread should be called CoInitialize separately. In addition, each thread must have its own ADOConnection .

I think you need to leave the idea of โ€‹โ€‹using a single global object / connection from this device. Just repeat the creation and destruction of objects in each thread. When the types of streams are different, then you can create a class of base streams on top of them. If the object is too large (has overhead in relation to the stream) or does not fit completely into the stream, divide it into the object.

At the moment, your question sounds like just a desire to maintain convenience, but if you really need to centralize participation in the ADO connection, you may be able to implement multi-page events for the connection events of both the main stream and other flows. Logging in should not be a problem for sequential connections: just save the input values โ€‹โ€‹and feed them to the streams.

+8
source share

While a different design might be a better solution, you can declare _MyObject as threadvar have a separate instance for each thread. Alternatively, you can move CoInitialize / CoUnitialize to the constructor / destructor of TMyObject.

I cannot give advice on when to create and free these instances, because I have no idea how your threads are created and freed.

+4
source share

All Articles