cuốn sách gpt4 ai đã làm

c++ - 尝试跨多个进程使用 Boost.Interprocess 消息队列时的断言

In lại Tác giả: Walker 123 更新时间:2023-11-28 05:10:18 33 4
mua khóa gpt4 Nike

我有以下精简程序,启动一堆子进程,然后使用 boost::interprocess::message_queue 向每个子进程发送消息。这在进程数量较少(我的机器上大约 4 个)时有效,但随着进程数量的增加,我收到以下消息:

head (81473): "./a.out"
Assertion failed: (res == 0), function do_wait, file /usr/local/include/boost/interprocess/sync/posix/condition.hpp, line 175.

我猜这是我的同步问题。是我做错了什么还是 boost::interprocess::scoped_lock 不够?

我的程序在这里:

#include 

#include
#include

#include

#include

auto main(int argc, char **argv) -> int
{
namespace ip = boost::interprocess;

boost::filesystem::path self{argv[0]};

if (argc == 1) {
std::cout << "head (" << ::getpid() << "): " << self << std::endl;

// create a message queue.
ip::message_queue::remove("work_queue");
ip::message_queue tasks{ip::create_only, "work_queue", 100, sizeof(int)};

// mutex for writing to the queue.
ip::interprocess_mutex mutex{};

// spawn off a bunch of processes.
const auto cores{5 * std::thread::hardware_concurrency()};
std::vector workers{};
for (auto i = 0; i < cores; ++i) {
workers.emplace_back(self, "child");
}

// send message to each core.
for (auto i = 0; i < cores; ++i) {
ip::scoped_lock lock{mutex};
tasks.send(&i, sizeof(i), 0);
}

// wait for each process to finish.
for (auto &worker : workers) {
worker.wait();
}
} else if (argc == 2 && std::strcmp(argv[1], "child") == 0) {
// connect to message queue.
ip::message_queue tasks{ip::open_only, "work_queue"};

// mutex for reading from the queue.
ip::interprocess_mutex mutex{};

unsigned int priority;
ip::message_queue::size_type recvd_size;

{
ip::scoped_lock lock{mutex};

int number;
tasks.receive(&number, sizeof(number), recvd_size, priority);
std::cout << "child (" << ::getpid() << "): " << self << ", received: " << number << std::endl;
}
}

trả về 0;
}

câu trả lời hay nhất

您在堆栈上创建一个 interprocess_mutex 实例。所以每个进程都有它自己的互斥量并且锁定它不会同步任何东西。您需要创建一个共享内存区域,将互斥量放在那里,然后在子进程中打开相同的共享内存区域以访问父进程创建的互斥量。

关于c++ - 尝试跨多个进程使用 Boost.Interprocess 消息队列时的断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43665399/

33 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress