2013-09-30 80 views
1

我是多線程新手,並且遇到了分段錯誤。我正在使用pthread_cond_broadcast無需在POSIX中忙等待

void addfunction(void *xyz) 
{ 
    flag_TO_go = 1; 
    pthread_cond_broadcast(&check_Queue2); 
    pthread_mutex_unlock(&get_mutex); 
} 

void delete_thread(void *abc) 
{ 
    while(1){ 
     pthread_mutex_lock(&get_mutex); 
     while (!flag_TO_go) {//condition variable 
      pthread_cond_wait(&check, &get_mutex); 
     } 
     flag_To_go= 1; 
     //things to do 
     //delete elemenst from a linked list 
     pthread_mutex_unlock(&get_mutex); 
    } 
} 

我得到的是一個段錯誤,因爲我的列表在第一個元素刪除後沒有任何元素。但我的線程正在鎖定並檢查它 是否有任何其他方式使用cond wait。

如果有人可以建議一種方法來做到這一點而不需要等待?

回答

0

試試這個..

void addfunction(void *xyz) 
{ 
    pthread_mutex_lock(&get_mutex); 
    flag_TO_go = 1; 
    pthread_cond_broadcast(&check_Queue2); 
    pthread_mutex_unlock(&get_mutex); 
} 

void delete_thread(void *abc) 
{ 
    while(1){ 
     pthread_mutex_lock(&get_mutex); 
     while (!flag_TO_go) {//condition variable 
      pthread_cond_wait(&check, &get_mutex); 
     } 
     flag_To_go= 0; 
     //things to do 
     //delete elemenst from a linked list 
     pthread_mutex_unlock(&get_mutex); 
    } 
} 
1

在設置flag_TO_go = 1addfunction之前,您需要鎖定互斥鎖。

如果要做的事情的真正含義起飛名單也許你應該使用flag_TO_go變量來檢查一個不空列表,而不是項。

此外,您將這兩個函數中的標誌設置爲1,我不明白這一點。你確定這是對的嗎?

+0

是的,我初始化flag_To_go 0全局所以每當信號到來。刪除功能將獲得鎖並執行刪除。我在將標誌設置爲1之前將互斥鎖鎖定。 是否有任何其他方式使用cond wait – user2825892

+0

@ user2825892:是的,將其全局設置爲0會發生一次。設置爲1後,它在哪裏設置爲0? –

+0

我不會將它更改爲0。因爲一旦我的名單得到了所有元素,我的線程(addfucntion)退出及deletefunction(線程)附加有權刪除,直到空的元素。所以這裏的情況是,如果我一個操作之後使flag_to_go = 0就不會再次檢查列表(和信號線,現在已經死了),如果我讓1.它開始檢查的元素,他們得到附加之前。 – user2825892