Manikandaraj Srinivasan
Manikandaraj Srinivasan

Reputation: 3647

Asynchronous function calls in C++

This is some code i'm using in Java for Making Asynchronous function calls in Java :

    public class AsyncLogger
    {
        public static asyncLog = null;
        public static ExecutorService executorService = Executors.newSingleThreadExecutor();

        public static AsyncLogger GetAsyncClass()
        {
            if(asyncLog == null)
            {
                asyncLog= new AsyncLogger();
            }
            return asyncLog;
        }


        public void WriteLog(String logMesg)
        {
            executorService.execute(new Runnable()
            {
                public void run()
                {
                    WriteLogDB(logMesg);
                }
            });
                }

                public void ShutDownAsync()
                {
                    executorService.shutdown();
        }
    }

This is a Singleton Class with static ExecutorService and WriteLogDB will be called as an Asynchronous function. So i can process my Code in WriteLogDB asynchronously without affecting the main flow.

Can i get a C++ equivalent like this ..?

Upvotes: 0

Views: 4924

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254431

std::thread([](){WriteLogDB(logMesg);}).detach();

or if you need to wait for a result:

auto result = std::async(std::launch::async, [](){WriteLogDB(logMesg);});
// do stuff while that's happening
result.get();

If you're stuck with a pre-2011 compiler, then there are no standard thread facilities; you'll need to use a third-party library like Boost, or roll you own, platform specific, threading code. Boost has a thread class similar to the new standard class:

boost::thread(boost::bind(WriteLogDB, logMesg)).detach();

Upvotes: 6

juanchopanza
juanchopanza

Reputation: 227370

You can make asynchronous functions calls using std::async from C++11.

Upvotes: 6

Related Questions