当我们在COM组件内部创建线程的时候,又是怎么样的一种情况呢?
这个地方跟组件的具体类型有关了,先来看看STA组件的情况。
STA组件内部创建线程
先看一段代码,CMyCarEx是一个STA组件,我们在Run()函数里面起了1000个线程。每个线程就会把m_nMiles加1,1000个线程运行完毕后通过连接点将英里数返回给调用者。
// MyCarEx.cpp : Implementation of CMyCarEx
#include "stdafx.h"
#include "MyCarEx.h"
#include <thread>
#include <vector>
// CMyCarEx
void CMyCarEx::WorkThread()
{
printf("CMyCarEx::WorkThread, begin, tid: %d\n", ::GetCurrentThreadId());
std::this_thread::sleep_for(std::chrono::milliseconds(10));
++m_nMiles;
printf("CMyCarEx::WorkThread, end, tid: %d, miles: %d\n", ::GetCurrentThreadId(), m_nMiles);
}
STDMETHODIMP CMyCarEx::Run()
{
// TODO: Add your implementation code here
std::vector<std::thread> vThreads;
for (int i = 0; i < 1000; ++i)
{
std::thread t(&CMyCarEx::WorkThread, this);
vThreads.push_back(std::move(t));
}
for (auto& t: vThreads)
{
t.join();
}
this->Fire_NeedMoreGas(m_nMiles);
return S_OK;
}
当客户端调用Run函数的时候,可以得到如下结果: