0

I would like to have your opinion for this general technical concept. (I am working on microsoft windows OS)

There is a Process, this process creates multiple threads for different tasks.

Main process: it is a windows service written by C# code. There are several threads that are create inside the main process: Thread_01, Thread_02, ...

Inside Thread_01: There is a Wrapper dll written in managed C++ to consume DLL_01. (DLL_01 is a dll written by me in native C++ code, that provides some APIs: Add, Remove, Connect)

Add and Remove can run very fast, but Connect may take more than 10 seconds and blocks the caller until it finishes.

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).

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 ?

Any recommendation is appreciated. Thanks in advance,

  • `std::async` 's behaviour is different on different platforms and different compiler versions, it may use internal thread pools. I think use `async` in background jobs is accetable. – prehistoricpenguin Jul 23 '21 at 03:01

1 Answers1

0

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. This takes care of a few of the issues above, though some are only shifted to the caller instead.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
  • Thanks for your comments @Ulrich. Regarding to your suggestion to use std::future<>, does this block call to connect? What I want t o do is to have a ConnectAsync instead of Connect to make it asynchronous. – Mohammad Yousefi Jul 25 '21 at 01:42