Understanding the com Suite (Part 1)

Source: Internet
Author: User

During the compilation of compile as "experiment on COM component thread model", I found that I could not reasonably explain the running status of the program under specific circumstances. To gain a better understanding of the COM thread model, reasonably explain the program running status, and find some materials. I found a good English article and translated it specially. For the callback processing of objects in the STA and the calling of objects in the MTA by threads in the RPC thread pool, this is the first time I have seen this article, and it is more in-depth than other materials, it is worth learning and thinking.

Source: http://www.codeguru.com/cpp/com-tech/activex/apts/article.php/c5529/Understanding-COM-Apartments-Part-I.htm

Com introduces a concurrency mechanism that intercepts and serializes concurrent calls to objects designed to process only one method call at a time. This mechanism is centered on the abstract boundary concept called "apartments. I found that about 40% of the problem was caused by a lack of understanding about the suite. This lack of knowledge is not surprising, because the suite is the most complex field in COM and is not well documented. Microsoft's goal is good, but when introducing a suite for com in Windows NT 3.51, they built a minefield for careless developers. By following the rules, you can avoid stepping on mines. However, if you do not know what the rules are, it is difficult to follow them.

This is the first part of a two-part series. The series of articles will explain what is a suite, where the suite exists, and how to avoid the introduction of the suite. The first part of the article will introduce com's suite-based concurrency mechanism; the second part will introduce some rules to avoid hidden and annoying bugs.

1 suite Basics

A suite is a concurrency boundary, a hypothetical box between objects and customer threads, used to isolate com customers and COM objects with incompatible thread features. The main purpose of a suite is to enable com to serialize method calls for non-thread-safe objects. If the COM object is not told to be thread-safe, com will not allow multiple calls to reach the object at the same time. On the contrary, if the COM object is told to be thread-safe, com will allow the object to process concurrent calls from multiple threads.

Every thread using COM and every object created by these threads are allocated to a suite. A suite cannot span process boundaries, so if objects are in different processes than their customers, they are in different suites. When a customer creates an in-process object, COM must decide whether to put it in the Creator's suite or another suite in the customer's process. If COM places the object and the thread for creating the object in the same suite, the customer will directly access the object. If COM places the object in another different suite, the call to the object by the thread of the created object will be called by the column set ).

Figure 1 shows the relationship between the thread and the object sharing suite, and when the thread and object are in different suites. The call in thread 1 will directly access the object created by the thread; the call in thread 2 will be performed through the proxy and Pile Foundation (stub. Com creates a proxy/pile foundation pair when the interface pointer column is set to the suite of thread 2. When passing interface pointers across the border of a suite, you must set the pointer columns. This is a rule. This means that if a custom interface is involved, even an in-process object, if it needs to communicate with customers in other suites, it still needs to provide the same interface as cross-process and cross-machine method calls, used for the proxy/pile foundation DLL supported by the column set (or the Type Library of the selected type library column set ).

Figure 1: calls to objects in other suites are column set, even if the object and caller belong to the same process

Windows NT 4.0 supports two types of suites, and Windows 2000 supports three types. The three types of suites are:

L single-threaded apartments (STA) (Windows NT 4.0 and Windows 2000)

L multi-threaded suites (MTA) (Windows NT 4.0 and Windows 2000)

L thread neutral Suite (neutral-threaded apartments, NTA) (Windows 2000 only)

Each thread can have only one single-threaded suite, but the number of objects that can be accommodated is unlimited. In addition, COM does not limit the number of STAS in the process. The first created STA in a process is called the master STA of the process. Objects in the sta are called and delivered to the stathread before delivery. Because all calls to objects are executed in the same thread, Stas-based objects cannot execute multiple calls at the same time. Com uses Stas to serialize calls to non-thread-safe objects. If it is not explicitly told that the COM object is thread-safe, com will put the object in the sta so that the object will not be accessed concurrently.

An interesting aspect about the sta operation is how com transfers the sta-based object call to the stathread. A hidden window is created at the time of creation of the VM instance. The Window Process of this window knows how to handle private messages that represent method calls. When the target is to exit the RPC channel of COM by calling the sta method, com will deliver a message representing this call to the sta window. After receiving the message, the thread in the sta distributes the message to the hidden window. The hidden window is sent to the pile foundation, and the pile foundation finally calls the object. Because a thread can only receive, distribute, and process one message at a time, the sta naturally and effectively calls the serial mechanism. 2. If n sta-based objects are called at the same time, the object is queued and then delivered to the object in sequence.

Figure 2: the request to enter the sta is converted to a message and delivered to the message queue. Messages in the message queue are converted back to method calls by the threads running in the STA.

The call is also important when you leave the STA. Com cannot block threads in the RPC channel, because callback may lead to deadlocks: Imagine when the stathread calls objects in other suites, what will happen when this object calls another object in STA in turn. If the stathread is blocked in the RPC channel, the call will never be returned, because the only thread that can handle the callback is waiting for the initial call to return in the RPC channel. Therefore, when calling and leaving the STA, com will block the stathread, but the stathread can still process the callback. To enable the callback to happen, com will track the causal relationship between each method call, so as to identify when the stathread is being released in the RPC channel and waiting for a method call to return, let it process another incoming call. By default, when the sta entry is called, if the stathread is waiting for an outgoing call to return, and the incoming call arriving does not belong to the same causal chain as the outgoing call waiting for the return, the incoming call is blocked. Writing a message filter can change this default behavior, which will be discussed in the next section.

Multi-threaded suites are completely different. Com limits that each process can have only one MTA, but does not limit the number of MTA midline processes and objects. The MTA does not hide the window and message queue. The call to the objects in the MTA is randomly passed to the threads in the RPC thread pool and will not be serialized (see figure 3 ). This means that the objects in the MTA should be thread-safe, because there is no external mechanism to ensure that the MTA-based objects receive only one call at a time, and the objects may be concurrently called by different RPC threads.

Figure 3: The call to enter the MTA is passed to the RPC thread instead of serialized.

For calls that exit the MTA, COM does not perform special processing. The call thread can be blocked in the RPC channel. If a callback occurs, no deadlock will be generated because the callback will be passed to another RPC thread.

Windows 2000 introduces the third suite type: thread-neutral suite, that is, NTA. Com limits that each process can have only one NTA. NTA does not allocate threads to NTA. NTA is only used to hold objects. The call to NTA-based objects does not cause thread switching, and the call thread enters NTA. That is to say, when the sta or MTA initiates a call to the NTA in the same process, the calling thread will temporarily leave its suite and directly execute the code in the NTA. This is different from the Objects Based on the STA and MTA: the calls of other suites to Objects Based on the STA and MTA always lead to thread switching. When calling a column set between different suites, thread switching takes up a lot of overhead. Excluding thread switching will improve the performance, so NTA is to make the cross-Suite Method Invocation more efficient. Windows 2000 supports an active-based external synchronization mechanism to specify whether to call NTA-based objects in a serialize manner. Activity-based serialization is more effective than message-based serialization. It can be performed at the object-to-object level.

2. How to allocate a suite to a thread

The thread that uses COM in any way must first call coinitialize or coinitializeex to initialize COM. When the two functions are called, the thread is placed into the suite. What kind of suite is put in depends on which function the thread calls and how to call it.

L if the thread calls coinitialize, com creates a new STA and puts the thread into it:

  Coinitialize (null); // sta

L if the thread calls coinitializeex and passes the coinit_apartmentthreaded parameter, the thread is also put into a sta:

  Coinitializeex (null, coinit_apartmentthreaded); // sta

L if coinitializeex is called and the coinit_multithreaded parameter is passed, the thread is put into the unique MTA in the process:

  Coinitializeex (null, coinit_multithreaded); // MTA

From a large scope, the process's suite configuration depends on how the thread in the process calls coinitialize [Ex]. There is a situation where com creates a suite without calling the coinitialize [Ex] function, but to make the problem simple, we will not discuss this situation for the moment (but for now we won't muddy the water by considering such circumstances ).

For example, if a new process is started, thread 1 in the process calls coinitialize:

  Coinitialize (null); // thread 1

Then thread 1 starts threads 2, 3, 4, and 5. These threads use the following statement to initialize COM:

  Coinitializeex (null, coinit_apartmentthreaded); // thread2

Coinitializeex (null, coinit_multithreaded); // thread3

Coinitializeex (null, coinit_multithreaded); // thread4

Coinitialize (null); // thread5

Figure 4 shows the final suite configuration. Threads 1, 2, and 5 are allocated to separate Stas, because each Stas can only have one thread. On the other hand, threads 3 and 4 are allocated to the MTA of the process. Remember: COM does not create multiple MTA instances for the process, but places any number of threads in a unique MTA.

Figure 4: A process has five threads distributed in three Stas and one MTA.

If you like the question (if you're a nuts and bolts person), you may be curious about the physical nature of the suite, that is, how com represents the suite internally. When a new suite is created, com will allocate the suite object on the stack and initialize it with important information such as the suite ID and suite type. When assigning a suite to a thread, com records the address of the corresponding suite object in the local thread storage (TLS. Therefore, if you want to know whether a thread belongs to a certain suite during execution in the com thread, you only need to find the address of the suite object in the local thread storage.

3. How to allocate a suite to objects in a process

This section describes how to assign a suite to an object. The algorithm used by com to determine which suite to create objects is different for In-process objects and out-of-process objects. In-process objects are more interesting, because only in-process objects can be created in the Creator's suite. We will first discuss in-process objects, and then discuss out-of-process objects.

Com reads the threadingmodel value of an object from the registry to determine which suite to create an in-process object. Threadingmodel is the name assigned to the inprocserver32 sub-key used to identify the object DLL. The following registry entries in regedit format identify the objects whose CLSID is 99999999-0000-0000-0000-111111111111, DLL is myserver. dll, and threadingmodel is apartment:

Apartment is one of the four thread models supported by Windows NT 4.0 and one of the five thread models supported by Windows 2000. The five thread models and the operating systems supporting the thread models are as follows:

The apartment type column indicates how com processes objects with the specified threadingmodel value. For example, the object with no threadingmodel value (threadingmodel = none) in COM is located in the master STA of the process; threadingmodel = apartment allows creation of objects in any sta (not just the master Sta; threadingmodel = Free restrict objects in MTA; threadingmodel = neutral restrict objects in NTA; threadingmodel = both allows com to create objects in Sta or MTA.

Com tries to place in-process objects to the suite of the Creator thread. For example, if the Stax thread creates an object identified as threadingmodel = apartment, com creates an object in the STA of the Creator thread. If the MTA thread creates an object with threadingmodel = Free, COM places the object in the MTA. However, sometimes com cannot place objects in the Creator's suite. For example, if the stathread creates an object identified as threadingmodel = free, the object will be created in the MTA of the process, and the Creator thread will access the object through proxy and pile foundation. Similarly, if the MTA thread creates an object with threadingmodel = none or threadingmodel = apartment, calls from the Creator thread will be transferred from the MTA column set to the object's sta.

The following table shows the conditions when the STA and MTA threads create an object with any valid threadingmodel value (or no threadingmodel value:

Why does threadingmodel = none restrict objects in the master STA of the process? Because only in this way can com safely execute multiple objects without knowing whether the object is thread-safe. Assume that two threadingmodel = none objects are created from the same DLL.

If the two objects access any global variables in the DLL, COM must execute all calls to these two objects in the same thread, otherwise, the two objects may try to read or write the same global variable at the same time. The restriction object in the master sta is the method in which com allows the object to be executed in the same thread.

The thread model provides important guidance for encoding. For example, the objects marked as threadingmodel = free or threadingmodel = both must be thread-safe, because MTA-based objects are not serialized during calling. Even threadingmodel = apartment objects should be partially thread-safe, because threadingmodel = apartment cannot prevent multiple objects from being created from the same DLL, resulting in conflicts on shared data.

The next part of this article will discuss this issue.

 

4How to allocate a suite for out-of-process objects

Non-process objects do not have threadingmodel values, because com uses completely different algorithms to allocate suites for non-process objects. In short, COM places out-of-process objects in the same suite as the server process of the created object. Most external (exe) com servers call coinitialize or coinitializeex to put the main thread into the STA. The server then creates class objects for the object types that can be created and registers them using coregisterclassobject. When an activation request arrives at the server initialized in this way, the request is processed in the STA of the process. As a result, the object created by the server process is also in the STA of the process.

You can move an out-of-process object to the MTA. You only need to place the registration Class Object thread in the MTA. In this way, the incoming activation request will arrive at the RPC thread executed in the MTA of the server process. The object created for the response request will also be in the MTA.

The main point is that in an EXE-type COM server, the suite where the thread that calls coregisterclassobject is located is also the suite where the object created by the server is located. Of course, there are also exceptions: Use the ccomautothreadmodule and ccomclassfactoryautothre of ATLAd-compiled exeThe COM server creates multiple Stas in the server process and distributes objects evenly among them. However, this only accounts for the existing exeA small part of the COM server can be considered as an exception, rather than a common rule.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.