简体   繁体   English

将 std::async 用于内部线程内的后台任务是否正确(不是来自主进程的线程)

[英]Is it correct to use std::async for background tasks inside an internal thread (not from main process's thread)

I would like to have your opinion for this general technical concept.我想听听您对这个通用技术概念的看法。 (I am working on microsoft windows OS) (我正在使用 microsoft windows 操作系统)

There is a Process, this process creates multiple threads for different tasks.有一个进程,这个进程为不同的任务创建多个线程。

Main process: it is a windows service written by C# code.主进程:是一个用C#代码编写的windows服务。 There are several threads that are create inside the main process: Thread_01, Thread_02, ...在主进程中创建了几个线程:Thread_01、Thread_02、...

Inside Thread_01: There is a Wrapper dll written in managed C++ to consume DLL_01. Thread_01 内部:有一个用托管 C++ 编写的 Wrapper dll 来消耗 DLL_01。 (DLL_01 is a dll written by me in native C++ code, that provides some APIs: Add, Remove, Connect) (DLL_01 是我用原生 C++ 代码编写的 dll,它提供了一些 API:添加、删除、连接)

Add and Remove can run very fast, but Connect may take more than 10 seconds and blocks the caller until it finishes. Add 和 Remove 可以运行得非常快,但 Connect 可能需要 10 秒以上的时间并阻塞调用者直到它完成。

I am thinking to use std::async to do the Connect function code, and send the result through a callback to the caller (main process).我正在考虑使用 std::async 来执行 Connect 函数代码,并通过回调将结果发送给调用者(主进程)。

Is it a good approach?这是一个好方法吗? I heard we cannot create or it is better not to create any thread inside inner threads, is it true?听说不能创建或者最好不要在内部线程中创建任何线程,是真的吗? If so, how about std::async ?如果是这样, std::async 怎么样?

Any recommendation is appreciated.任何建议表示赞赏。 Thanks in advance,提前致谢,

None of what you describe makes the use of threads inacceptable for your code.您所描述的任何内容都不会使您的代码无法接受线程的使用。

As usual, threads have issues that need to be cared for:像往常一样,线程存在需要处理的问题:

  • Data races due to access to shared data.由于访问共享数据而导致数据竞争。
  • Problems of ownership of resources is now not just "Who own what?"资源所有权的问题现在不仅仅是“谁拥有什么?” but "Who and when owns what?".但是“谁以及何时拥有什么?”。
  • When a thread is blocked and you want to abort this operation, how do you cancel it without causing issues down the line?当一个线程被阻塞并且你想中止这个操作时,你如何取消它而不导致问题? In your case, you must avoid calling the callback, when the receiver doesn't exist any more.在您的情况下,当接收者不再存在时,您必须避免调用回调。

Concerning your approach of using a callback, consider std::future<> instead.关于您使用回调的方法,请考虑std::future<> This takes care of a few of the issues above, though some are only shifted to the caller instead.这解决了上面的一些问题,尽管有些只是转移到调用者身上。

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

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