Mutex锁定哈希图会降低性能

问题描述 投票:0回答:1

我有一个用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,token,buf);
            pthread_mutex_unlock(&hashTable_write_mutex);
        }
        index++;
    }
c linux multithreading operating-system mutex
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.