简体   繁体   English

如何安全删除ATL DLL中的std :: thread

[英]How to safely remove std::thread in ATL DLL

I wrote an ATL DLL and I have problem with std::thread witch I used to run asyn method. 我写了一个ATL DLL,我曾经用过运行asyn方法的std::thread巫婆有问题。 I implemented method that performs operations asynchronously. 我实现了异步执行操作的方法。 The problem occurs when a client tries to remove the object class in which thread already done. 当客户端尝试删除已经完成线程的对象类时,就会发生此问题。

This is my code: 这是我的代码:

STDMETHODIMP CQRCodeGenerator::GenerateAsync(QRCodeTypeEnum QRCodeType, QRCodeFormatEnum QRCodeFormat, LONG QRCodePx, BSTR ImageFile)
{

if (ImageFile == nullptr) ImageFile = L"";

//stack to log file
OPFHelper::add_execute_method(this, L"CQRCodeGenerator::GenerateAsync",
    std::vector<std::wstring>{OPFHelper::ConvertToWSting((LONG)QRCodeType),
    OPFHelper::ConvertToWSting((LONG)QRCodeFormat), OPFHelper::ConvertToWSting((LONG)QRCodePx), ImageFile});

t = std::thread(&CQRCodeGenerator::run, this, QRCodeType, QRCodeFormat, QRCodePx, ImageFile);
return S_OK;
}

void CQRCodeGenerator::run(enum QRCodeTypeEnum QRCodeType, enum QRCodeFormatEnum QRCodeFormat, LONG QRCodePx, BSTR ImageFile)
{

 ......

Fire_OnGenerate(this,ImageFile, _pQRCode, _pInvoiceID, _pQRCodeMD5, _pKS,nullptr);
}   
  1. std::thread is declared in .h file .h文件中声明了std::thread
  2. when I reception event and I try delete obj QRCodeGenerator I get error. 当我接收事件并尝试删除obj QRCodeGenerator出现错误。

I know that this is a problem with the removal of the thread of memory, because I carried out synchronous function Generate which did not give error. 我知道这与删除内存线程有关,因为我执行了同步函数Generate ,但没有出错。

But I don't know how Can I delete this thread and detect when Client wants to delete obj. 但是我不知道如何删除该线程并检测Client何时要删除obj。 The second thing it can not understand why there is a problem with releasing memory when thread-assistant no longer works. 第二件事,它无法理解线程辅助不再起作用时释放内存的原因。

Do you call std::thread::join() or detach() before destroying the thread? 在销毁线程之前,您是否调用std::thread::join()detach() Otherwise the std::thread destructor is supposed to trigger terminate() and abort the program. 否则,应该使用std::thread析构函数触发terminate()并中止程序。

If something is owning the thread (as " client tries to remove the object class in which thread already done " suggests), the object might call t.join() in its destructor, for example. 如果某物拥有该线程(如“ 客户端尝试删除已经完成线程的对象类 ”建议),则该对象可能在其析构函数中调用t.join()

Also note that you shouldn't destroy the object inside of Fire_OnGenerate - that is called in the scope of the running thread. 另请注意,您不应破坏Fire_OnGenerate内部的对象-在运行线程的范围内调用该对象。 So you would basically destroy a thread which is still running (it only can complete after Fire_OnGenerate returns back). 因此,您基本上将销毁一个仍在运行的线程(只有在Fire_OnGenerate返回后才能完成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM