Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

send/recv的时序有要求么? #16

Closed
regomne opened this issue Aug 10, 2020 · 1 comment
Closed

send/recv的时序有要求么? #16

regomne opened this issue Aug 10, 2020 · 1 comment

Comments

@regomne
Copy link

regomne commented Aug 10, 2020

我想问一下在使用ipc::channel的时候,是不是一方的recv必须在另一方的send之前调用?
我测试了下Tutorial中的ipc::channel的例子,一旦在thread producer的cc.recv调用之前加入一个sleep,那么就收不到消息了,而且奇怪的是对应的consumer方调用的send依然会返回成功?

测试代码如下:

int main()
{
    using namespace std::literals;

    std::vector<char const*> const datas = {
    "hello!",
    "foo",
    "bar",
    "ISO/IEC",
    "14882:2011",
    "ISO/IEC 14882:2017 Information technology - Programming languages - C++",
    "ISO/IEC 14882:2020",
    "Modern C++ Design: Generic Programming and Design Patterns Applied"
    };

    // thread producer
    std::thread t1{ [&] {
        ipc::channel cc { "my-ipc-channel" };
        for (std::size_t i = 0; i < datas.size(); ++i) {
            // try sending data
            while (!cc.send(datas[i])) {
                // waiting for connection
                cc.wait_for_recv(1);
            }
            std::this_thread::sleep_for(1s);
            // recv ack
            std::printf("1 recving\n");
            auto dd = cc.recv();
            auto str = static_cast<char*>(dd.data());
            if (str == nullptr) {
                std::printf("ack: error!\n");
            }
            else {
                std::printf("ack: %c\n", str[0]);
            }
        }
        // quit
        cc.send(ipc::buff_t('\0'));
    } };

    // thread consumer
    std::thread t2{ [&] {
        ipc::channel cc { "my-ipc-channel" };
        while (1) {
            std::printf("2 recving\n");
            auto dd = cc.recv();
            auto str = static_cast<char*>(dd.data());
            if (str == nullptr || str[0] == '\0') return;
            std::printf("2 recv: %s\n", str);
            // try sending ack
            while (!cc.send(ipc::buff_t('a'))) {
                // waiting for connection
                cc.wait_for_recv(1);
            }
        }
    } };

    t1.join();
    t2.join();
}
@mutouyun
Copy link
Owner

嗯,对的。

其实严格来说,是 recv 端 connect 之前的消息不会缓存。而默认 ipc::channel 只是个 sender,只有调用了 recv 之后才会自动升级为 receiver。

之前写的 Tutorial 太久没更新了,ipc 的 send 返回值也确实有点问题。
我更新了一下,修正了问题点(包括 Tutorial,改成了你的这段测试代码)。
你拉取最新的代码,再按新的示例调整一下即可。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants