【问题标题】:Sending void* object through message queue[linux]通过消息队列发送 void* 对象[linux]
【发布时间】:2013-04-02 14:32:46
【问题描述】:

所以,我实现了自己的 mpi 库(简化版本),我需要在进程之间发送/接收一些数据。 MPI_Send 看起来像这样(void *buf,int count,datatype data,etc...)。所以这意味着我需要发送指向 buf 地址的数据类型(char、double 或 int)的计数元素。我需要通过消息队列(mq)发送 em。 MPI_Recv 采用相同的参数。目前这是我在发送和接收中所做的:

    //Sender part of code
    ret=mq_send(mq,buf,sizeof(buf),0);
        if(ret < 0)
    return MPI_ERR_IO;
    //Receiver part of code
    ret = mq_receive(mq, buf, MSGSIZE, NULL );
    if(ret < 0)
    return MPI_ERR_IO;

现在我只接收数组的第一个元素。我将如何发送整个事情?这是我的想法

    //Sender part of pseudocode
    for(i=0,count)
       element=(cast to datatype)buf[i]; 
       mq_send(mq,element,sizeof,0);
    //Receiver part of pseudocode
    //i receive the count number of elements prior to this message
    for(i=0,count)
       mq_receive(mq,local_variable,etc...)
       somehow store them into my void *buf which i receive as an argument ??

如果有不清楚的地方,我会回复

【问题讨论】:

    标签: c unix mqueue


    【解决方案1】:

    您使用 mq_send 的第三个参数指定要放入队列的数据量。你的情况是:

    ret=mq_send(mq,buf,sizeof(buf),0);
    

    假设 buf 在某处被初始化

    float f[2];
    void *buf = f;
    

    那么表达式sizeof(buf)的意思是:称为“buf”的指针的大小。虽然它可能适用于某些架构,但正确的方法是

    ret=mq_send(mq,buf,sizeof(float) * <number of elements>, 0);
    

    表示浮点数的大小乘以存储在数组中的浮点数。

    在这种情况下,您会将整个数组放入队列中。您还可以避免迭代并仅使用恒定数量的消息,而不是线性数字。

    【讨论】:

    • 我太笨了,我实际上尝试过,但我决定创建一个 if/case 并执行 sizeof(datatype)* count 我只尝试了 sizef(char)*count。现在可以了,非常感谢:)
    猜你喜欢
    • 2014-03-29
    • 2012-10-20
    • 2017-04-27
    • 2023-04-10
    • 2018-02-02
    • 1970-01-01
    • 2014-02-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多