【发布时间】:2013-10-08 03:54:12
【问题描述】:
据我了解,如果两个或多个线程试图同时访问同一个内存块,它至少应该“抱怨”。
我正在为一个计算回文的类编写一个程序(列表中前后出现的单词也算在内)。在我的多线程解决方案中,我生成了 26 个线程来处理字母表中的每个字母
int error = pthread_create(&threads[i], NULL, computePalindromes, args);
compute palindrome 只是遍历单词的子列表:
void * computePalindromes(void * arguments) {
struct arg_struct *args = (struct arg_struct *)arguments;
int i;
for (i = args->start; i < args->end; i++) {
if (quickFind(getReverse(array[i]), 0, size - 1)) {
printf("%s\n", array[i]);
}
}
return NULL;
}
现在,应该导致程序停止的段。我修改了 quickSelect 以在列表中找到相反的单词。
int quickFind(char * string, int lower_bound, int upper_bound) {
int index = ((upper_bound + lower_bound) / 2);
//sem_wait(&semaphores[index]);
if (upper_bound <= lower_bound) return (strcmp(string, array[index]) == 0);
if (strcmp(string, array[index]) > 0) {
//sem_post(&semaphores[index]);
return quickFind(string, (index + 1), upper_bound);
} else if (strcmp(string, array[index]) < 0) {
//sem_post(&semaphores[index]);
return quickFind(string, lower_bound, (index - 1));
} else return 1;
}
你可以看到我注释掉了一堆 sem_post/waits。
【问题讨论】:
-
没有什么会“抱怨”。如果您在一个线程中写入某个地址并在另一个不同步的情况下读取 - 您可能会读取不正确的数据。在这种情况下,您不会写入任何共享缓冲区 - 只是从中读取。取决于最初用数据填充数组的代码 - 它可能相当不错。
-
另一点是不保证 MT 安全的代码会失败。希望是。在实践中,糟糕的代码可以通过许多测试而不会出错,但很少会失败。
标签: c multithreading pthreads