【发布时间】:2016-06-23 13:47:53
【问题描述】:
我有一个我无法解决的问题。 我必须制作一个由某个线程共享的数据结构,问题是: 线程同时执行,它们应该在特定结构中插入数据,但是每个对象都应该在互斥锁中插入,因为如果一个对象已经存在,则不能重新插入。 我已经考虑过创建一个数组,其中线程放置它们正在工作的对象的键,如果另一个线程想要放置相同的键,它应该等待当前线程完成。 所以,换句话说,每个线程都为锁元素执行这个函数:
void lock_element(key_t key){
pthread_mutex_lock(&mtx_array);
while(array_busy==1){
pthread_cond_wait(&var_array,&mtx_array);
}
array_busy=1;
if((search_insert((int)key))==-1){
// the element is present in array and i can't insert,
// and i must wait for the array to be freed.
// (i think that the problem is here)
}
array_busy=0;
pthread_cond_signal(&var_array);
pthread_mutex_unlock(&mtx_array);
}
在我完成对象后,我使用以下函数释放数组中的键:
void unlock_element(key_t key){
pthread_mutex_lock(&mtx_array);
while(array_busy==1){
pthread_cond_wait(&var_array,&mtx_array);
}
array_busy=1;
zeroed((int)key);
array_busy=0;
pthread_cond_signal(&var_array);
pthread_mutex_unlock(&mtx_array);
}
这样,每次执行结果都会发生变化(例如:程序第一次插入300个对象,第二次插入100个对象)。
感谢您的帮助!
更新:
@DavidSchwartz @Ashor 我修改代码如下:
void lock_element(key_t key){
pthread_mutex_lock(&mtx_array);
while((search_insert((int)key))==-1){
//wait
pthread_cond_wait(&var_array,&mtx_array);
}
pthread_mutex_unlock(&mtx_array);
}
还有……
void unlock_element(key_t key){
pthread_mutex_lock(&mtx_array);
zeroed((int)key);
pthread_cond_signal(&var_array);
pthread_mutex_unlock(&mtx_array);
}
但不起作用..它的行为方式与以前相同。
我还注意到函数 search_insert(key); 的一个奇怪行为
int search_insert(int key){
int k=0;
int found=0;
int fre=-1;
while(k<7 && found==0){
if(array[k]==key){
found=1;
} else if(array[k]==-1) fre=k;
k++;
}
if (found==1) {
return -1; //we can't put the key in the array
}else {
if(fre==-1) exit(EXIT_FAILURE);
array[fre]=key;
return 0;
}
}
从不进去
if(found == 1)
【问题讨论】:
-
当您已经在使用互斥锁时,为什么还需要
array_busy变量? -
为什么这被否决了?
-
互斥锁(mtx_array)用于锁定变量array_busy,只有被锁定才能使用这个变量。
-
您的代码毫无意义。您对
array_busy==1的任何检查都不会永远触发,因为没有线程解锁互斥锁,而array_busy的值不是零,并且没有线程访问或修改array_busy而不持有互斥锁。 -
您粘贴的代码不完整。您在 if 语句(或 search_insert 调用)中丢失了代码,即使您怀疑可能是错误所在。我也猜想那里的代码会解释很多你粘贴的关于array_busy的代码。
标签: c multithreading mutex