gpt4 book ai didi

c - 当由多个线程执行时,我应该同步 mq_timedreceive 调用吗?

转载 作者:IT王子 更新时间:2023-10-29 01:17:52 25 4
gpt4 key购买 nike

我在 Linux 上使用 Posix 消息队列。基本上,我有多个线程通过调用 mq_timedreceive 从同一个队列接收消息。

如果多个线程同时运行且队列不为空,我是否可以保证消息不会被多次接收(即消息不会被传递到多个线程)?

可以肯定的是,我可以将接收与互斥锁同步,但我想尽可能避免这种锁定。我阅读了所有手册页 (man mq_overview(3)),但没有找到任何明确的内容。

提前致谢。

最佳答案

内核会为您进行锁定。

查看ipc/mqueue.c中的实现:

SYSCALL_DEFINE5(mq_timedreceive, mqd_t, mqdes, char __user *, u_msg_ptr,
size_t, msg_len, unsigned int __user *, u_msg_prio,
const struct timespec __user *, u_abs_timeout)
{
...
struct mqueue_inode_info *info;
...
filp = fget(mqdes);
if (unlikely(!filp)) {
ret = -EBADF;
goto out;
}

inode = filp->f_path.dentry->d_inode;
...
spin_lock(&info->lock);
if (info->attr.mq_curmsgs == 0) {
if (filp->f_flags & O_NONBLOCK) {
spin_unlock(&info->lock);
...
} else {
msg_ptr = msg_get(info);

inode->i_atime = inode->i_mtime = inode->i_ctime =
CURRENT_TIME;

/* There is now free space in queue. */
pipelined_receive(info);
spin_unlock(&info->lock);
ret = 0;
}

每个 mqueue 都有一个自旋锁,它在检查新消息之前获取。

最后一个 else (pipelined_receive) 是消息出队的地方。这是由 info->lock 保护的,因此两个线程不可能获得相同的消息。

关于c - 当由多个线程执行时,我应该同步 mq_timedreceive 调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9520095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com