• C++ 操作共享内存


    #include <sys/time.h>
    #include <string>
    #include <sys/mman.h>
    #include <fcntl.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include<string.h> 
    #include<iostream>
    using namespace std;
    #include <thread>
    
    char* AttachShmBuf(string ringUrl, uint64_t &len)
    {
        int fd = open(ringUrl.c_str(), O_RDWR | O_EXCL ,S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
    
    	if (-1 == fd)
    	{
            std::cout << "fd null" <<std::endl;
    		return NULL;
    	}
    
    	struct stat filestat;
    	if((fstat(fd, &filestat)) != 0)
    	{
    		close(fd);
    		fd = 0;
            std::cout << "fstat null" <<std::endl;
    		return NULL;
    	}
    
    	len  = filestat.st_size;
    
    	char* buf = (char *)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    
    	return buf;
    }
    void ringfunc(int index)
    {
        string filepath= "./ring1m";
        uint64_t len = 0;
        char* pRing =AttachShmBuf(filepath,len);
        if(!pRing)
        {
            std::cout << "ring null" <<std::endl;
            return ;
        } 
        for(;;)
        {
            if(index==0)
            {
                memset(pRing,1,len-1);
            }else
            {
                for(uint64_t i=0;i<len-1;i++)
                {
                    char r=pRing[i];
                }  
            }
            std::cout << "index:" << index << " len "<<len  <<std::endl;
            usleep(100);
        }
    }
    
    int main(int argc,char* argv[])
    {
    
    
        string filepath= "./ring1m";
        uint64_t len = 0;
        char* pRing =AttachShmBuf(filepath,len);
    	char* pRing1 =AttachShmBuf(filepath,len);
    	char* pRing2 =AttachShmBuf(filepath,len);
        if(!pRing || !pRing1)
        {
            std::cout << "ring null" <<std::endl;
            return 0;
        }
        memset(pRing,0,len);
        int index =0 ;
       
        for(;;)
        {
            memset(pRing,1,len-1);
    		//memset(pRing1,2,len-1);
    		for(uint64_t i=0;i<len;i++)
    		{
    			char r=pRing1[i];
    		}
    		for(uint64_t i=0;i<len/2;i++)
    		{
    			char r=pRing2[i];
    		}
            std::cout << "index:" << index++ << " len "<<len <<std::endl;
            usleep(100);
        }
    
    
        for (uint8_t i = 0; i < 4; i++)
        {
            thread t(ringfunc, i);
            t.detach(); 
        }
        getchar();
        std::cout<<"----"<<endl;
        exit(0);
    
        return 0;
    }
    

      

  • 相关阅读:
    我在华为做敏捷测试的那些流程
    精简测试用例编写
    五步定位性能瓶颈
    敏捷软件测试--初见
    并发用户数与TPS之间的关系
    关于CSS样式的那些事_导航条菜单讲解
    关于字符串的一些简单编码题
    设置div控件居中的方法
    sqlplus登录Oracle时ORA-01017: invalid username/password; logon denied的错误
    java中的foreach输出数组中的元素
  • 原文地址:https://www.cnblogs.com/a9999/p/13637048.html
Copyright © 2020-2023  润新知