【发布时间】:2020-07-08 16:34:17
【问题描述】:
我有一个用 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++;
}
【问题讨论】:
-
恐怕您的程序会受到许多其他竞争条件的影响。假装你可以只用
hashTable_write_mutex做一个ht_get()会适得其反,哈希表的大小会增长,并在你的第一种情况下移动它的所有元素。
标签: c multithreading pthreads hashtable mutex