Skip to content

Tutorial

木头云 edited this page Mar 29, 2019 · 15 revisions

示例程序:demo

ipc::route

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::route cc { "my-ipc-route" };
    // waiting for connection
    while (cc.recv_count() == 0) {
        std::this_thread::yield();
    }
    // sending datas
    for (std::size_t i = 0; i < datas.size(); ++i) {
        cc.send(datas[i]);
    }
    // quit
    cc.send(ipc::buff_t('\0'));
}};

// thread consumer
std::thread t2 {[&] {
    ipc::route cc { "my-ipc-route" };
    while (1) {
        ipc::buff_t dd = cc.recv();
        auto str = static_cast<char*>(dd.data());
        if (str == nullptr || str[0] == '\0') return;
        std::printf("recv: %s\n", str);
    }
}};

t1.join();
t2.join();

ipc::channel

// 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);
        }
        // recv ack
        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) {
        auto dd = cc.recv();
        auto str = static_cast<char*>(dd.data());
        if (str == nullptr || str[0] == '\0') return;
        std::printf("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();

Home
Tutorial

namespaces

classes

head files

Clone this wiki locally