From : http://blog.csdn.net/zj510/article/details/39053647
一个STA对象只能属于一个STA套间,那么一个STA对象一定是在一个线程里面运行的。所以STA对象不需要考虑并发,因为它永远是串行运行的。
那么一个MTA对象在哪个线程里面运行的?
MTA套间调用MTA对象
看下面这段代码:
- // TestCom.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <atlbase.h>
- #include <atlcom.h>
- #include "../MyCOM/MyCOM_i.h"
- #include "../MyCOM/MyCOM_i.c"
- #include <iostream>
- #include <thread>
- using namespace std;
- void WorkThread()
- {
- CoInitializeEx(0, COINIT_MULTITHREADED);
- WCHAR temp[100] = { 0 };
- swprintf_s(temp, L"thread tid: %d\n", ::GetCurrentThreadId());
- ::OutputDebugStringW(temp);
- {
- CComPtr<IMyRect> spRect;
- HRESULT hr = spRect.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
- hr = spRect->Draw(CComBSTR(L"red"));
- }
- CoUninitialize();
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- CoInitializeEx(0, COINIT_MULTITHREADED);
- WCHAR temp[100] = {0};
- swprintf_s(temp, L"main tid: %d\n", ::GetCurrentThreadId());
- ::OutputDebugStringW(temp);
- {
- CComPtr<IMyRect> spRect;
- spRect.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
- spRect->Draw(CComBSTR(L"red"));
- CComPtr<IMyRect> spRect2;
- spRect2.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
- spRect2->Draw(CComBSTR(L"blue"));
- }
- std::thread t(WorkThread);
- std::thread t1(WorkThread);
- std::thread t2(WorkThread);
- CoUninitialize();
- t.join();
- t1.join();
- t2.join();
- return 0;
- }
// TestCom.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <atlbase.h>
#include <atlcom.h>
#include "../MyCOM/MyCOM_i.h"
#include "../MyCOM/MyCOM_i.c"
#include <iostream>
#include <thread>
using namespace std;
void WorkThread()
{
CoInitializeEx(0, COINIT_MULTITHREADED);
WCHAR temp[100] = { 0 };
swprintf_s(temp, L"thread tid: %d\n", ::GetCurrentThreadId());
::OutputDebugStringW(temp);
{
CComPtr<IMyRect> spRect;
HRESULT hr = spRect.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
hr = spRect->Draw(CComBSTR(L"red"));
}
CoUninitialize();
}
int _tmain(int argc, _TCHAR* argv[])
{
CoInitializeEx(0, COINIT_MULTITHREADED);
WCHAR temp[100] = {0};
swprintf_s(temp, L"main tid: %d\n", ::GetCurrentThreadId());
::OutputDebugStringW(temp);
{
CComPtr<IMyRect> spRect;
spRect.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
spRect->Draw(CComBSTR(L"red"));
CComPtr<IMyRect> spRect2;
spRect2.CoCreateInstance(CLSID_MyRect, NULL, CLSCTX_INPROC_SERVER);
spRect2->Draw(CComBSTR(L"blue"));
}
std::thread t(WorkThread);
std::thread t1(WorkThread);
std::thread t2(WorkThread);
CoUninitialize();
t.join();
t1.join();
t2.join();
return 0;
}
主线程初始化MTA套间,辅助线程也是。
COM对象都是运行在创建它的线程里面。
STA套间调用MTA对象
MTA对象是运行在系统创建的线程里面,看前面一篇文章。