PTypes: multithreading: jobqueue

Top: Multithreading: jobqueue

>     #include <pasync.h>

>     class jobqueue {
>         jobqueue(int limit = DEF_QUEUE_LIMIT);

>         void post(message* msg);
>         void post(int id, int param = 0);
>         void posturgent(message* msg);
>         void posturgent(int id, int param = 0);
>         message* getmessage(int timeout = -1);

>         int get_count();
>         int get_limit();
>     }

The jobqueue class implements a thread-safe list of objects of type message or any derivative class. Jobqueue supports posting to and reading from the list from multiple threads simultaneously.

The jobqueue class can help to build multithreaded server/robot applications by maintaining a pool of reusable threads that receive job 'assignments' from a queue. This threading model can be faster compared to applications that create and destroy separate thread objects for each task. See Examples for a full-featured server template with a thread pool.

jobqueue::jobqueue(int limit = DEF_QUEUE_LIMIT) constructs a job queue object. Limit specifies the maximum number of messages this queue can hold. If the limit is reached, the next thread that posts a message will wait until the queue becomes available again. In this version the default for limit is 5000.

void jobqueue::post(message* msg) adds a message to the queue. Msg can be an object of class message or any derivative class. The message object should always be created dynamically using operator new. The messages in the queue are processed in order they were posted, i.e. on first-in-first-out basis.

void jobqueue::post(int id, pintptr param = 0) creates a message object using id and param and calls post(message*).

void msgqueue::posturgent(message* msg) posts a message object "out of turn", i.e. this message will be processed first. The messages posted through this method are processed on first-in-last-out basis. post() and posturgent() can be used alternately on the same queue.

void jobqueue::posturgent(int id, pintptr param = 0) creates a message object using id and param and calls posturgent(message*).

message* jobqueue::getmessage(int timeout = -1) retrieves the next message from the queue or waits if there are no messages available. The timeout parameter specifies the timeout value in milliseconds. If timeout is -1 (the default) getmessage() will wait for a message infinitely. This function returns a message object, or otherwise NULL if the time specified in timeout has elapsed. NOTE: the message object returned by this function must be freed with operator delete. It is safe to call getmessage() concurrently.

int jobqueue::get_count() returns the number of messages currently in the queue.

int jobqueue::get_limit() returns the queue limit set by the constructor.

See also: message, msgqueue, Examples

PTypes home