我有一个用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++;
}