gpt4 book ai didi

c - 使用二进制信号量实现计数信号量

转载 作者:行者123 更新时间:2023-11-30 16:46:21 24 4
gpt4 key购买 nike

我已经实现了某种用户级线程系统。我需要一些帮助来使用二进制信号量来实现计数信号量实现(向上和向下功能如下所述)。这是我实现的二进制信号量的接口(interface):

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);

这是计数信号量接口(interface)的接口(interface):

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);

我尝试做的是 void up(structcounting_semaphore* sem)锁定值。但是正如您在下面看到的那样,这还不够。我已经在有问题的情况下添加了评论。

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);
}

最佳答案

sem->value达到0时,线程阻塞,需要重新调度。你没有显示你的调度代码,所以我无法给出具体的建议。调度程序可能应该代表线程调用bsem_up(sem->binary_descriptor);

关于c - 使用二进制信号量实现计数信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43801718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com