2013-08-23 70 views
0

我實現循環緩衝器如下:此循環緩衝區實現是否需要信號量?

long windex = 0, rindex = 0, count = 0; 

producer_ISR() /* whenever the data avail, then gets the interrupt */ 
{ 
    /* store the data in array buffer */ 
    array[windex] = data; 

    windex++; 
    count = count + 1; /* Increment the count */ 

    if (windex == 32) /* overflow condition */ 
     windex = 0; 
} 

consumer 
{ 
    while(1) 
    { 
      if(count > 0) 
      { 
      /* process the data */ 
      data1 = array[rindex]; 

      rindex++; 
      count = count - 1; /* decrement the count */ 

      if (rindex == 32) /* overflow condition */ 
       rindex = 0; 
      } 
    } 
} 

這是否代碼需要,以保護該共享變量「計數」的上述兩種功能之間的信號量?

根據我的分析,信號量不是必需的,請分享您的想法。

回答

1

如果可以有多個使用者,則需要一個信號量,因爲2個使用者可以檢查計數,然後使用相同的元素,或者可以嘗試消耗一個不存在的元素。

類似的生產者。

如果只能有1個消費者和1個生產者,則只需要一個信號量,如果count = count + 1和/或count = count - 1不是原子的。如果它不是原子,這樣的事情可能發生:

count = 1 // initial value 
Get count for "count = count + 1" as 1 
Get count for "count = count - 1" as 1 
count = 1 + 1 = 2 
count = 1 - 1 = 0 

然後,你必須count = 0時候,居然有等待的項目。

另請注意,如果緩衝區填滿,代碼可能需要一些錯誤檢查。

+0

我認爲count = 1/0互斥量比信號量更方便,對不對? –