进程之间条件变量的同步

#include 
#include 
#include 
#include 
#include 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

struct timespec hipretime;
struct processMsg {
    uint64_t timenow;
    uint32_t frameId;
    processMsg()
    {
        timenow = 0;
        frameId = 0;
    }
};
/*************************************
Function:
Author  :
Date    : 2019/10/26
*************************************/

int main()
{
    try {
        std::cout<<"Pub begin....."<("processMsg")();
        boost::interprocess::interprocess_mutex* mtx =
            managed_shm.find_or_construct("mtx")();
        boost::interprocess::interprocess_condition* cnd =
            managed_shm.find_or_construct("cnd")();
        //boost::interprocess::scoped_lock lock(*mtx);
        while (shm_msg->frameId < 20000) {
            // pub 先启动
            clock_gettime(CLOCK_MONOTONIC, &hipretime);
            shm_msg->timenow = (uint64_t)(hipretime.tv_sec * 1000000000) + hipretime.tv_nsec;  //将时间写入内存
            shm_msg->frameId++;
            cnd->notify_all();
            usleep(100000);
             std::cout<<"Pubing....."<wait(lock); //等待读取共享内存完毕
        }
        cnd->notify_all();  //避免永远等待信号
    } catch (...) {
    }
    boost::interprocess::shared_memory_object::remove("shm");
}
#include 
#include 
#include 
#include 
#include 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
struct timespec hipretime;
struct processMsg {

    uint64_t timenow;
    uint32_t frameId;
    processMsg()
    {
        timenow = 0;
        frameId = 0;
    }
};
/*************************************
Function:
Author  :
Date    : 2019/10/26
*************************************/

int main()
{
    try {
        std::cout<<"sub begin ....."<("processMsg")();
        boost::interprocess::interprocess_mutex* mtx =
            managed_shm.find_or_construct("mtx")();
        boost::interprocess::interprocess_condition* cnd =
            managed_shm.find_or_construct("cnd")();
 
         
        while (shm_msg->frameId < 20000) {
            processMsg current_msg;
            boost::interprocess::scoped_lock lock(*mtx);
            cnd->wait(lock);   
            //std::cout<<"sub is waked"<timenow);
            std::cout<frameId;       
        }
    } catch (...) {
    }
    boost::interprocess::shared_memory_object::remove("shm");
}

上图代码需要在linux平台下编译,编译命令:

g++ -L /usr/lib/x86_64-linux-gnu/librt.so -o sub process_sub.cpp -lrt -pthread

g++ -L /usr/lib/x86_64-linux-gnu/librt.so -o pub process_pub.cpp -lrt -pthread

指令说明: -L指定所需要库的路径,这个库路径要修改成自己的真实路径

你可能感兴趣的:(C++)