2016-10-07 20:56:34 +00:00
|
|
|
//
|
|
|
|
// AsyncTaskQueue.hpp
|
|
|
|
// Clock Signal
|
|
|
|
//
|
|
|
|
// Created by Thomas Harte on 07/10/2016.
|
|
|
|
// Copyright © 2016 Thomas Harte. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
#ifndef AsyncTaskQueue_hpp
|
|
|
|
#define AsyncTaskQueue_hpp
|
|
|
|
|
|
|
|
#include <memory>
|
|
|
|
#include <thread>
|
|
|
|
#include <list>
|
|
|
|
#include <condition_variable>
|
|
|
|
|
2016-10-23 01:58:45 +00:00
|
|
|
#ifdef __APPLE__
|
|
|
|
#include <dispatch/dispatch.h>
|
|
|
|
#endif
|
|
|
|
|
2016-10-07 20:56:34 +00:00
|
|
|
namespace Concurrency {
|
|
|
|
|
2016-10-07 21:18:46 +00:00
|
|
|
/*!
|
|
|
|
An async task queue allows a caller to enqueue void(void) functions. Those functions are guaranteed
|
2017-05-15 11:38:59 +00:00
|
|
|
to be performed serially and asynchronously from the caller. A caller may also request to flush,
|
2016-10-07 21:18:46 +00:00
|
|
|
causing it to block until all previously-enqueued functions are complete.
|
|
|
|
*/
|
2016-10-07 20:56:34 +00:00
|
|
|
class AsyncTaskQueue {
|
|
|
|
public:
|
|
|
|
AsyncTaskQueue();
|
|
|
|
~AsyncTaskQueue();
|
|
|
|
|
2016-10-07 21:18:46 +00:00
|
|
|
/*!
|
|
|
|
Adds @c function to the queue.
|
|
|
|
|
|
|
|
@discussion Functions will be performed serially and asynchronously. This method is safe to
|
|
|
|
call from multiple threads.
|
|
|
|
@parameter function The function to enqueue.
|
|
|
|
*/
|
2016-10-07 20:56:34 +00:00
|
|
|
void enqueue(std::function<void(void)> function);
|
2016-10-07 21:18:46 +00:00
|
|
|
|
|
|
|
/*!
|
|
|
|
Blocks the caller until all previously-enqueud functions have completed.
|
|
|
|
*/
|
2016-10-20 01:15:04 +00:00
|
|
|
void flush();
|
2016-10-07 20:56:34 +00:00
|
|
|
|
|
|
|
private:
|
2016-10-23 01:58:45 +00:00
|
|
|
#ifdef __APPLE__
|
|
|
|
dispatch_queue_t serial_dispatch_queue_;
|
|
|
|
#else
|
2016-10-07 20:56:34 +00:00
|
|
|
std::unique_ptr<std::thread> thread_;
|
|
|
|
|
|
|
|
std::mutex queue_mutex_;
|
|
|
|
std::list<std::function<void(void)>> pending_tasks_;
|
|
|
|
std::condition_variable processing_condition_;
|
2016-10-07 21:08:29 +00:00
|
|
|
std::atomic_bool should_destruct_;
|
2016-10-23 01:58:45 +00:00
|
|
|
#endif
|
2016-10-07 20:56:34 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif /* Concurrency_hpp */
|