我有一個問題,我無法解決。 我不得不做一個線程共享的數據結構,問題是: 線程是同時執行的,它們應該在特定的結構中插入數據,但每個對象都應該被插入互斥鎖中,因爲如果一個對象存在它不能重新插入。 我想過如果另一個線程想要放置相同的密鑰,它應該等待當前線程完成,那麼線程會放置它們正在工作的對象的鍵。 所以,換句話說,每一個線程執行此功能鎖定元素:C -Mutex數據結構與多線程
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);
}
後,我有我自由與後續的功能在ARRY重點對象完成:
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個對象)。
感謝您的幫助!
UPDATE:
@DavidSchwartz @Asthor我修改了代碼如下:
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'變量? – EOF
爲什麼這是downvoted? – arunmoezhi
互斥鎖(mtx_array)用於鎖定變量array_busy,只有在鎖定的情況下,我纔可以使用此變量。 – Flank