S
S
samokiller2021-01-29 07:18:05
C++ / C#
samokiller, 2021-01-29 07:18:05

How to call a function in parallel so that it survives after the calling function ends?

I am writing a dll for an external program.
The a(string str) function in Dll must accept strings, save them to a vector, process the accumulated data after X milliseconds and pass the result to the b(string result) function, which sometimes saves it to SharedMemory, and sometimes to the database.

The data comes very often, i.e. the function can be called hundreds of times per second.

Waiting for SharedMemory to be released or for a query to the database to pass is very long, so I want to send the result of processing from a() to b() and immediately return from a().

1. Is it possible that with such a frequent function call, the data in the vector will be distorted or not completely written? The order of the entries is not important.

2. How to release the function b(result) into free swimming? At first I thought to do

thread th(b);
th.detach();

but then I realized that if it was a regular program, and not a dll, then th would not have had time to complete it, because the calling function would have ended.
I suppose that in dll, as well as in exe, it also will not have time to complete it.

Do I understand correctly that the only solution for b(result) to finish when a(str) has already ended and returned control is to write a separate exe for b() and run it as a separate process?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2021-01-29
@SaNNy32

1. Is it possible that with such a frequent function call, the data in the vector will be distorted or not completely written? The order of the entries is not important.

If the data is written in one stream, then there will be no distortion. Use synchronization primitives on different threads.
How to release the function b(result) into free swimming? At first I thought to do
thread th(b);
th.detach();
but then I realized that if it was a regular program, and not a dll, then th would not have had time to complete it, because the calling function would have ended.
I suppose that in dll, as well as in exe, it also will not have time to complete it.

Why doesn't the function in the thread have time to complete it? Are you unloading a dll from a process?
It is possible to make such an implementation.
A queue is created. In the first thread, data is added to the queue. The second thread reads the data from the queue and processes it. The result of the work is transferred to the second queue. The third thread reads data from the second queue and writes it to the database or SharedMemory. If there is no data, then the thread simply waits for new data. Actions with queues in different threads must be synchronized through synchronization primitives (mutex).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question