互斥锁锁定哈希图会降低性能

我有一个用C编写的程序,用于使用多个线程对文件中单词的频率进行计数。 我希望程序在添加线程时会变快,但是在添加线程时性能会变慢。 我已经将问题调试成我的代码的哈希表部分具有的互斥锁,这是我使用的唯一共享变量。 如何正确使用锁以确保更好的性能?

//Tokenize file contents
char **tokens=tokenizeFileContents(fileContent);

//Loop to iterate over all tokens and store frequencies
while(1){
    if(tokens[index]==NULL){
        break;
    }
    char * token=tokens[index];


    pthread_mutex_lock(&hashTable_mutex);
    if(ht_get(ht,token)==NULL){

        ht_set(ht,token,"1");

        pthread_mutex_unlock(&hashTable_mutex);
    }

    else{
        pthread_mutex_unlock(&hashTable_mutex);
        pthread_mutex_lock(&hashTable_write_mutex);
        int count=atoi(ht_get(ht,token))+1;
        char buf[32];
        snprintf(buf,sizeof(buf),"%d",count);
        ht_set(ht,buf);
        pthread_mutex_unlock(&hashTable_write_mutex);
    }
    index++;
}
sushe302 回答:互斥锁锁定哈希图会降低性能

如何正确使用锁以确保更好的性能?

在您的特定任务中,似乎每个线程在没有互斥锁的情况下填充其自己的哈希映射是最有效的。线程完成后,将其哈希表汇总为一个(用于匹配哈希映射键的总和)。

您可能还希望对输入数据进行分区,以为每个线程分配自己的块,这样它们就不会竞争从输入数据中读取下一个元素的情况。

本文链接:https://www.f2er.com/2565285.html

大家都在问