zeromq / cppzmq

Header-only C++ binding for libzmq
http://www.zeromq.org
MIT License
1.95k stars 757 forks source link

When I use this class to define an object in the heap area, calling Send is non-blocking, and the defined object is blocking in the stack area #592

Open heipi666 opened 1 year ago

heipi666 commented 1 year ago

class Pusher { public: Pusher(const std::string& addr) : context(1), socket(context_, ZMQ_PUSH) { try { int send_buffersize = 1024 * 1024; socket.setsockopt(ZMQ_SNDBUF,&send_buffer_size,sizeof(send_buffersize)); socket.connect(addr.c_str()); } catch (const zmq::error_t& e) { // 错误处理 std::cerr << "Error occurred: " << e.what() << std::endl; exit(1); } }

int Send(const std::string& data) {
    zmq::message_t msg(data.size());
    memcpy(msg.data(), data.data(), data.size());
    int ret = ERROR;
    try {
        ret = socket_.send(msg);
        if (ret == -1) {
            std::cerr << "Error sending data: " << zmq_strerror(errno) << std::endl;
            exit(1);
        }
    }
    catch (const zmq::error_t& e) {
            // 错误处理
            std::cerr << "Error occurred: " << e.what() << std::endl;
            exit(1);
    }
    return ret;
}

int Send(const char *buff,int len) {

    if(buff == NULL)
    {
        std::cerr << "Buff is Empty!\n" << std::endl;
        exit(1);
    }
    zmq::message_t msg(len);
    memcpy(msg.data(), buff, len);
    int ret = ERROR;
    try {
        ret = socket_.send(msg);
        std::cerr << "send ret : " << ret << std::endl;
        if (ret != 0) {
            std::cerr << "Error sending data: " << zmq_strerror(errno) << std::endl;
            exit(1);
        }
    }
    catch (const zmq::error_t& e) {
            // 错误处理
            std::cerr << "Error occurred: " << e.what() << std::endl;
            exit(1);
    }
    return ret;
}

private: zmq::contextt context; zmq::sockett socket; };

caicaiking commented 1 year ago

if you want to call send funciton in non-block behavior , can you add the ZMQ_DONTWAIT flag to send function. maybe this can help you.

heipi666 commented 1 year ago

Thank you for your answer, I didn’t mean that, I meant that the send function should be blocked by default, but when I use this class to define an object in the heap area, calling the send function becomes non-blocking

gummif commented 1 year ago

Can you write a minimal program where this happens?