Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous threads in standard C++

I wonder how could I implement an asynchronous call in standard C++.

I have a image/video processing program and I want to add another function/feature but I would like it to be run in a another thread or to be run asynchronously to the original thread.

I just want to notify the main thread when something happened in this new thread. (This does not happen always and there is no reason why the main thread should wait for this new process to end. Hence I prefer an asynchronous call, if that is simpler than multithread programming)

I hope I am in the right path.

Thanks in advance.

Ignacio.

UPDATE: Currently I am not using any thread library yet because up until now I didn't need it. I was thinking in Boost ... is it a good idea? Where should I start If I want to get to work some asynchronous calls?

like image 608
nacho4d Avatar asked Sep 14 '10 17:09

nacho4d


People also ask

Does C support asynchronous?

With the new C++11 standard, there is std::async . Pretty much anything the machine is capable of can be done in C, you just have to do it yourself.

What are asynchronous threads?

asynchronous threading - the parent and child run concurrently/independently of one another. Multithreaded servers typically follow this model.

Does STD async use threads?

If the async flag is set, then a callable function will be executed in a separate thread. If the deferred flag is set, a callable function will be stored together with its arguments, but the std::async function will not launch a new thread.

What is asynchronous programming in C?

What is asynchronous programming? Asynchronous programming is an effective way to reduce the delay or wait time that is happening in the code. It avoids the following scenario - an activity is blocked in a synchronous process, which will in turn block the entire application by blocking the other tasks from executing.


1 Answers

The current C++ standard doesn't define such a thing, but C++0x does. That leaves a couple of choices. The cleanest is to probably use a current implementation that includes the C++ future class (and relatives). This seems to be exactly the sort of thing you're looking for. Depending on the compiler you're using, support may already be packaged (e.g., I believe it's normally included in gcc 4.5), or you might want/need to use the Boost version (though I don't believe it's part of the official Boost release -- you need to look in the vault).

Otherwise, you can do something on your own with spawning a thread pool and submitting a task to it. If you decide to, my advice would be to follow the standard interface for a future as closely as possible; it's almost inevitable that at some point you'll have futures available, and probably prefer to use them instead of maintaining your own version.

like image 127
Jerry Coffin Avatar answered Sep 28 '22 06:09

Jerry Coffin