简体   繁体   English

在C中为* nix创建线程安全定时队列

[英]Creating thread safe timed queue in C for *nix

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 parts of my program that can keep messages in memory X seconds. 我在程序的各个部分之间需要某种定时队列,可以将消息保留在内存中X秒。 X don't change while this timed queue exists. 存在此定时队列时,X不变。

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. 当第一条消息在X队列中排队时, tqueue_pop()应该阻塞并返回。

What is the best way to do this? 做这个的最好方式是什么? Maybe there are some already existing solutions? 也许有一些已经存在的解决方案?

Language: C 语言:C

OS: *nix 操作系统:* 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. 您应该能够在POSIX Message Queues之上构建它,并让它处理大多数细节。 Something like: 就像是:

(1) write queue with a time stamp field (1)使用时间戳字段写入队列

(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). (2)在您的其他线程中,要么阻塞mq_receive()直到出现消息(或者使用mq_notify()为您发信号或创建线程)。

(3) Read the queue and check the time stamp. (3)阅读队列并检查时间戳。

(4) Calculate the time difference for how long you have to wait and use select() or some sleep/timer mechanism. (4)计算需要等待多长时间并使用select()或某种睡眠/计时器机制的时间差。

(5) Process the message. (5)处理消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM