栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

无法读取共享内存

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

无法读取共享内存

我发现了几个问题,但是,我不确定它们是否可以解决您的问题。

  1. name
    shm_open
    应开始
    /
    携带使用。
  2. read
    publish
    演员一定不能丢弃
    volatile
    。例如:
    const uint64_t newVal = *(uint64_t volatile*)_ptr;
    。更好的是,丢弃
    volatile
    并使用
    std::atomic

尽管涉及不同的过程,但是仍然存在相同的对象被多个执行线程访问的情况,并且这些线程中的至少一个会修改共享对象。


我进行了上述更改。使用

std::atomic
固定的:

class SHM {    void* _ptr;public:    SHM() {        const auto handle = shm_open("/myTest", O_RDWR|O_CREAT, 0666);        const auto size =  4 * 1024 * 1024;        if (-1 == ftruncate(handle, size)) throw;        _ptr = mmap(0,size , PROT_READ | PROT_WRITE, MAP_SHARED, handle, 0);        if(_ptr == MAP_FAILED) throw;    }    bool read(uint64_t& magic, uint64_t& time) {        auto p = static_cast<std::atomic<uint64_t>*>(_ptr);        const uint64_t newVal = p[0];        if (newVal != magic) { magic = newVal; printf("value changed!!!n"); time = p[1]; return true;        }        return false;    }    void publish(const uint64_t time) {        auto p = static_cast<std::atomic<uint64_t>*>(_ptr);        p[0] += time;        p[1] = time;    }};void sender() {    SHM shm;    timespec t;    for (auto i = 0; i < 10000; i++) {        if (0 == clock_gettime(CLOCK_REALTIME, &t)) { const uint64_t v = t.tv_sec * 1000 * 1000 * 1000 + t.tv_nsec; shm.publish(v); printf("published %lun", v); usleep(100);        }    }}void reader() {    SHM shm;    uint64_t magic = 0;    uint64_t t = 0;    while (true) {        if (shm.read(magic, t)) { printf("%lu, %lun", magic, t);        }    }}int main(int ac, char**) {    if(ac > 1)        reader();    else        sender();}

有了

std::atomic
您,您可以拥有更多控制权。例如:

struct Data {    std::atomic<uint64_t> time;    std::atomic<uint64_t> generation;};// ...    bool read(uint64_t& generation, uint64_t& time) {        auto data = static_cast<Data*>(_ptr);        auto new_generation = data->generation.load(std::memory_order_acquire); // 1. Syncronizes with (2).        if(generation == new_generation) return false;        generation = new_generation;        time = data->time.load(std::memory_order_relaxed);        printf("value changed!!!n");        return true;    }    void publish(const uint64_t time) {        auto data = static_cast<Data*>(_ptr);        data->time.store(time, std::memory_order_relaxed);        data->generation.fetch_add(time, std::memory_order_release);  // 2. (1) Synchronises with this store.    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/399180.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号