2017-05-05 79 views
0

我已經實現了用戶級別的線程系統。我需要一些幫助來實現計數信號量,使用二進制信號量實現(上下函數如下所述)。 這裏是我的執行二進制信號的接口:使用Binary-Semaphore實現計數信號量

typedef enum BinSemStatus{ 
    locked, 
    unlocked 
} BinSemStatus; 


struct semaphore { 
BinSemStatus status; 
int bid; 
}; 

int bsem_alloc();//allocate a new binary semaphore,return its descriptor 
void bsem_free(int id); 
void bsem_down(int id); 
void bsem_up(int id); 

這裏是計數信號接口的接口:

struct counting_semaphore* counting_alloc(uint value); 
counting_free(struct counting_semaphore* sem); 

// If the value representing the count of 
// the semaphore variable is not negative, decrement it by 1. If the 
// semaphore variable is now 
// negative, the thread executing acquire is blocked until the value is 
// greater or equal to 1. 
// Otherwise, the thread continues execution. 
void up(struct counting_semaphore* sem); 
// Increments the value of semaphore 
// variable by 1. 
void down(struct counting_semaphore* sem); 

我所試圖做的是無效了(結構counting_semaphore * sem) 來鎖定value.But正如你可以看到,這是不夠的。我已經在有問題的情況下添加了一條評論。

struct counting_semaphore { 
int binary_descriptor; 
int value; 
}; 

void down(struct counting_semaphore *sem){ 
    bsem_down(sem->binary_descriptor); 
    if (sem->value > 0){ 
    sem->value--; 
    } 
    else{ 
    //not sure what to do here, maybe use anather semaphore in some way? 
    } 
    bsem_up(sem->binary_descriptor); 
} 
void up(struct counting_semaphore *sem){ 
    bsem_down(sem->binary_descriptor); 
    sem->value++; 
    bsem_up(sem->binary_descriptor); 
} 
+0

'counting_free(結構counting_semaphore * SEM);' - >'無效counting_free(結構counting_semaphore * SEM);' – 4386427

+0

你有沒有試過編寫任何代碼了嗎? – 4386427

+0

問題是什麼? –

回答

0

關鍵部分由sem-> binary_descriptor1保護,並且每個向下(S)和向上(S)操作都使用它來正確更新sem.value的值 更新這兩個操作後,釋放sem-> binary_descriptor2信號量只有在值爲正數時 S.value從不是負數,因爲執行向下(S)的任何進程在sem-> binary_descriptor2處被阻止。

struct counting_semaphore* counting_semaphore_alloc(int value) { 

    struct counting_semaphore* sem = malloc(sizeof(struct counting_semaphore)); 
    sem->value = value; 
    sem->binary_descriptor1= bsem_alloc();//locks the value 
    sem->binary_descriptor2= bsem_alloc();//locks the sing of the value 
    if (value <= 0) { 
     bsem_down(sem->binary_descriptor2); 
    } 
    return sem; 
    } 

void down(struct counting_semaphore *sem){ 
    bsem_down(sem->binary_descriptor2); 
    bsem_down(sem->binary_descriptor1); 
    sem->value--; 
    if (sem->value>0){ 
     bsem_up(sem->binary_descriptor2); 
    } 
    bsem_up(sem->binary_descriptor1); 
} 


void up(struct counting_semaphore* sem) { 
    bsem_down(sem->binary_descriptor1); 
    sem->value++; 
    if (sem->value == 1) { 
     bsem_up(sem->binary_descriptor2); 
    } 
    bsem_up(sem->binary_descriptor1); 
} 
0

sem->value達到0時,該線程的塊,並且它是時間重新安排。你沒有顯示你的日程安排代碼,所以我不能給出具體的建議。可能調度程序應該代表線程調用bsem_up(sem->binary_descriptor);