我很好奇重复使用的可能性
CWinThread
。例如,我有以下类(互斥体和错误检查被省略):
class MyClass
{
friend UINT ThreadFunc(void* parameter);
public:
MyClass()
{
m_thread = AfxBeginThread(ThreadFunc, this, 0, 0, CREATE_SUSPENDED);
m_thread->m_bAutoDelete = false;
}
~MyClass() { delete m_thread; }
int Value() const { return m_value; }
void Calculate(int value)
{
m_value = value;
m_thread->ResumeThread();
}
private:
CWinThread* m_thread = nullptr;
int m_value = 0;
};
inline UINT ThreadFunc(void* parameter)
{
auto* mc = reinterpret_cast<MyClass*>(parameter);
mc->m_value *= 2;
return 0;
}
Calculate
方法(目前我的类在第一次调用后不进行计算),类似这样:MyClass mc;
mc.Calculate(1);
// Waiting for mc to finish...
std::cout << mc.Value() << std::endl;
mc.Calculate(2);
// Waiting for mc to finish...
std::cout << mc.Value() << std::endl;
我只能假设,可以创建 somo 类型的作业队列并在循环中检查它,直到线程停止。
CWinThread 有一个事件队列,如果它工作在用户界面模式下,可以接收消息,请参阅用户界面线程,但是通过 Windows 消息传递工作不是很快或类型安全,最好实现自己的任务队列或使用一个如果您想要良好的性能或类型安全,可以从任何库中获取。