自定义共享hashmap实现

时间:2012-03-29 16:23:19

标签: c algorithm hash hashmap

我见过很多共享的hashmap实现。以下是我要解决的具体方案。

我正在尝试在多处理器系统中进行分层聚类。让我们说我在'n'处理器中运行'n'个线程。让输入的总数为K.在第一次迭代中,我们必须找到所有对之间的距离(k ^ 2)并将它们存储在哈希映射中。为了使这个多线程,我分配每个处理器(K ^ 2 / n)输入对进行处理。

现在距离结果必须存储在某种哈希映射中以用于下一次迭代。每个处理器还输出它找到的最小距离。合并所有处理器之间距离最小的那对。

在下一次迭代中,我们需要找到这个新合并的对与所有其他(k-2)输入的距离。并将这些新距离与已存储在哈希表中的所有其他对的距离进行比较。

由于哈希表上存在并发写入,因此使用带锁的单个哈希表会有效地破坏并行性。

系统的一个要求是,每个线程都不会获得上次获得的相同对。因此,它必须读取由其自身和其他线程生成的哈希值,以找到已存储的距离。

所以我提出了以下想法:

    -Each thread has its own hash table and has access to the hash table of other threads.
    -Iteration -1 : No read is performed this time since the hash tables are empty.  So each thread just writes to its own hash table.
    -Iterations 2 : Each thread is going to generate some new pairs.  But for all the other old pairs it needs to read the hash_maps to find the distance (might be its own hash_map or the hash_map of other threads).
    -Iterations 3 to k-1 : Same as iteration 2.

为了改善从迭代2到k-1的并行性,我设计了以下想法:

            - store the newly generated values in a new hashmap.
            - for old values keep reading the old hash_maps.  Since concurrent reads can be done, this phase is completely parallel.
            - for each entry in the new hash_map
                      find the which threads's hashmap has this entry.  Replace the old value by the new value.  This step might be effectively sequential because we have to both read and write at the same time.

这是一个有效的想法吗?如果您对如何改进这一点有任何建议,请告诉我。特别是,对于第三步 - 这是整个想法的瓶颈。如果有一个有效的实现可以实现此步骤的最大并行度,那么它会很棒。

我使用谷歌的稀疏哈希库作为hash_map。

1 个答案:

答案 0 :(得分:3)

所以这样做的一种方法是只使用一个分段的哈希映射 - 有N个映射,每个映射存储带有0 mod n,1 mod n等的哈希值。然后,你只需要锁定一个n-thth哈希映射一次。由于您希望读取比写入更常见,因此您可以使用共享锁进行读取,使用独占锁进行写入,这将进一步降低您的争用。

您还可以进行“随机播放步骤”,其中每个线程负责对特定存储桶的所有写入,而不是每个线程写入它计算的值。线程首先会将新值写入与哈希表桶相对应的队列(您可以使用各种争用最小化方式),然后每个线程将使用单个队列并在一个大的队列中执行对其单个哈希表的所有写入go - 无争用。