[python-win32] problem accessing OPC clients from thread

Tim Roberts timr at probo.com
Mon Dec 3 23:33:11 CET 2007


Jeff Peery wrote:
>
> Graham,
>
> thanks for the beta! I think my main problem is that I don’t really
> understand this code; I didn’t write it. Could you recommend a
> book/website that describes what these functions like
> ‘group.OPCItems.AddItem’ do? For example I don’t really know what a
> ‘group’ is or what the addItem() parameters are, or how to interpret
> that error code that you interpreted, and I’m not really sure if this
> code will work for other OPC servers other than the automation direct
> server.
>

Although I can understand your frustration, I want to make sure you
understand that the trouble you reported has nothing to do with the OPC
tools or their usage.  It is quite complicated to use COM objects in a
multithreaded application.  A COM object is allowed to declare itself as
single-threaded; in that case, COM takes extra steps to transfer control
over to a single thread before calling that object.

To do that, COM has to have some per-thread data structures to
communicate between threads.  The way that setup gets done is by calling
the CoInitialize API (exposed in Python as pythoncom.CoInitialize).  If
a multithreaded application expects to use COM objects in several
threads, it is REQUIRED to call CoInitialize from every thread.  The
pywin32 library will call CoInitialize on the main thread for you, but
YOU are responsible for calling it from your secondary threads.

-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the python-win32 mailing list