#ifndef ASYNC_H #define ASYNC_H #include "Fifo.h" typedef void *(*pthread_function_t)(void *); class AsyncOperation { protected: enum { failed = -1, uninitialized = 0 , initialized, running, done } state; public: virtual void performOperation() = 0; int getState() { return state; } virtual ~AsyncOperation() {} virtual bool shouldExit() { return false; } } ; class CannotEnqueue { int reason; public: static const int BUFFER_FULL = 0; static const int ERROR = -1; CannotEnqueue( int reason ) : reason( reason ) { } int getReason() { return reason; } }; class AsyncQueue { private: class ExitThreadOperation : public AsyncOperation { public: ExitThreadOperation() { state = initialized; } ~ExitThreadOperation() {} bool shouldExit() { return true; } void performOperation() { } } ; NonLockingFifo< AsyncOperation * > operations; bool isThreadStarted; pthread_t thread; public: /* Creates a queue that can have up to initialNumOps in it. * If the user tries to enqueue more than that number of ops, * an exception is thrown. */ AsyncQueue( size_t numOps ); //Adds an operation to the end of the Queue. void enqueue( AsyncOperation *ao ) throw( CannotEnqueue ); //Starts the Queue int start(); bool isRunning(); //waits for all enqued operations to finnish //void wait(); //causes the thread to stop after completing all currently //enqueued operations. This will block until the thread is stopped. int stop(); //note that this calls stop: ~AsyncQueue(); size_t getCapacity() { return operations.getCapacity(); } //size_t getNumOperationsInQueue() { return operations.numAvailable(); } } ; #endif /*ASYNC_H*/