2017-05-05 77 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);