开发者

Creating thread safe timed queue in C for *nix

开发者 https://www.devze.com 2023-02-05 02:29 出处:网络
One part of my program creates some kind of messages. These messages are then processed in the second part.

One part of my program creates some kind of messages. These messages are then processed in the second part.

I need some kind of timed queue between p开发者_StackOverflowarts of my program that can keep messages in memory X seconds. X don't change while this timed queue exists.

Ideally this should look like this:

tqueue_t *tqueue_new(int seconds);
int tqueue_push(tqueue_t *queue, void *msg);
void *tqueue_pop(tqueue_t *queue);

tqueue_pop() should block and return when first message was in queue for X seconds.

What is the best way to do this? Maybe there are some already existing solutions?

Language: C

OS: *nix

Also, this queue should work in threaded evironment.


You should be able to build this on top of POSIX Message Queues and let it take care of most of the details. Something like:

(1) write queue with a time stamp field

(2) In your other thread either block on mq_receive() until a message comes in (or use mq_notify() to signal or create the thread for you).

(3) Read the queue and check the time stamp.

(4) Calculate the time difference for how long you have to wait and use select() or some sleep/timer mechanism.

(5) Process the message.

0

精彩评论

暂无评论...
验证码 换一张
取 消