线程安全的哈希表 [英] Thread-safe HashTable

查看:32
本文介绍了线程安全的哈希表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 HashTable 字段的类.我需要如何实现 getset 方法来独占写入 HashTable,但非独占读取?

I have a class which contains a HashTable field. How I need to implement get and set methods for exclusive writing to HashTable, but non-exclusive reading?

private Hashtable _data = new Hashtable();

public object this[object key]
{
    get {} // must be non-exclusive 
    set {} // must be exclusive
}

我需要我自己的getter和setter实现.没有任何额外的框架助手(我在面试时问了这个问题).

I need my own implementation of getter and setter. Without any additional framework helpers (I asked this question on interview).

推荐答案

假设允许锁定和等待锁定,那么下面的逻辑应该可以工作(注意它使用了Java的语义.不知道是否适用到 c#):

Assuming that locking and waiting on a lock is allowed, then the following logic should work (Note that it uses Java's semantics. I don't know whether it applies to c#):

Object lock
bool write = false
int reads = 0

write(..) {
    synch(lock) {
        while (write || reads > 0) 
            lock.wait();
        write = true;
    }

    ...

    synch(lock) {
        write = false;
        lock.notifyAll();
    }
}

read() {
    synch(lock) {
        while (write) 
            lock.wait();
        reads ++;
    }

    ...

    synch(lock) {
        if (--reads == 0)
            lock.notifyAll();
    }
}

这篇关于线程安全的哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆