COM线程模型之二[译]

来源:互联网 发布:淘宝群怎么添加到首页 编辑:程序博客网 时间:2024/05/16 01:06

[原文]http://msdn.microsoft.com/en-us/library/ms809971.aspx

Behavior of the COM Threading Models

Before any thread can create or manipulate COM objects, it must perform some preliminary initialization to establish its relationship with the COM library. As a result of this process, COM creates an apartment appropriate for the initialization routine: CoInitialize creates a single-threaded apartment (STA), whereas CoInitializeEx with the COINIT_MULTITHREADED flag produces a multi-threaded apartment. The CoInitialize/CoInitializeEx call does not initialize the COM library globally, only the calling thread's use of it, so it's important to remember that this initialization should be done on a per-thread basis. This is typically done early in a thread's work function (ThreadProc).

A single-threaded apartment is associated with the thread that created it, and only that specific thread may execute calls on objects within the apartment. By contrast, a multi-threaded apartment is not associated with any particular thread. It may be called concurrently by any number of threads and objects within it and should subsequently protect their member data.

Communication between apartments is done via marshaling, a generic abstraction for passing data across thread or process boundaries. Because calls to single-threaded apartments can only be executed on the thread that created them, other threads that wish to use an object within this apartment marshal the call to the apartment's thread and let the apartment thread execute the call. The apartment thread then marshals the return value back to the calling thread.

 

COM线程模型的行为

在任何一个线程创建或者操作COM对象之前,必须执行一些初始化的操作用于建立与COM库之间的关系.COM根据不同的初始化创建对应的套间:CoInitialize创建单线程套间(STA),CoInitializeEx参数为COINIT_MULTITHREADED时创建多线程套间(MTA).这两个操作并不会作用在这个COM库上,他们只是对调用的线程有效.所以,为每个线程进行初始化操作十分重要.

一个单线程与创建它的线程关联,只有这个线程才能调用这个套间内的对象.与此相反,一个多线程套间不会与任何特定线程关联.它可能被套间内的多个线程和多个对象并发调用.因此需要保护他们的成员数据.

套间之间通讯可以通过列集解决.列集是一个抽象的概念,主要用于在进程边界或者线程之间传送数据.因为在单线程套间中的调用只能在创建套间的线程中执行,其他打算使用这个套间中的对象的线程列集这个调用,然后由套间线程执行这个操作.这个套间的线程紧接着会列集返回值到调用线程.

 

原创粉丝点击