-3

我有许多读取缓存数据的读取器线程,例如

struct {
   hash_table *cache;
   int64_t version;
} ctx;

许多读取器线程读取缓存,例如

void *get_from_cache(void *key)
{
    /* Maybe access invalid address when writer thread free it too quickly ! */
    /* I can use setjmp/longjmp to deal the exception, but it's too expensive ! */
    /* On Windows, I can use SEH, but how about Linux ? */

    /* Finally, can I avoid it with zero cost on reader thread ? */

    return cache.get(key);
}

只有一个写入器线程更新缓存:

void update_cache()
{
    int64_t new_version = get_current_version();

    if (new_version > ctx.version) {
        hash_table *new_cache = load_cache();
        hash_table *old_cache = ctx.cache;

        ctx.version = new_version;
        ctx.cache = new_cache;

        /* How to determine the wait time is enough ? */
        /* Just use a experiential value ? */
        wait_some_time();

        free_hash_table(old_cache);
    }
}

感谢您的帮助。

4

1 回答 1

0

从标题看来,您似乎正试图依赖指针操作的原子性质。请看一下是否更改指针被认为是 C 中的原子动作?.

另外 - 试图检测无效的内存访问真的很糟糕。如果你得到一个指向一个有效但不正确的地址的指针怎么办。

我会使用更传统的同步机制。

于 2013-01-06T14:13:18.717 回答