您的位置:首页 > 其它

COM线程模型 - MTA接口 - Part IV - (运行线程)

2014-11-07 11:29 405 查看
From : http://blog.csdn.net/zj510/article/details/39053647
一个STA对象只能属于一个STA套间,那么一个STA对象一定是在一个线程里面运行的。所以STA对象不需要考虑并发,因为它永远是串行运行的。

那么一个MTA对象在哪个线程里面运行的?

MTA套间调用MTA对象

看下面这段代码:

[cpp]
view plaincopyprint?

// 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对象是运行在系统创建的线程里面,看前面一篇文章。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐