gpt4 book ai didi

c - 用互斥锁重新创建 sem_wait()?

转载 作者:太空宇宙 更新时间:2023-11-04 02:59:07 26 4
gpt4 key购买 nike

有什么办法可以让我在同一个互斥锁中拥有最多 10 个线程?

类似于 sem_wait() 的值 10

编辑:

找到这个:

它是信号量的一个实现,使用了互斥量和条件变量。

typedef struct {
int value, wakeups;
Mutex *mutex;
Cond *cond;
} Semaphore;

// SEMAPHORE

Semaphore *make_semaphore (int value)
{
Semaphore *semaphore = check_malloc (sizeof(Semaphore));
semaphore->value = value;
semaphore->wakeups = 0;
semaphore->mutex = make_mutex ();
semaphore->cond = make_cond ();
return semaphore;
}

void sem_wait (Semaphore *semaphore)
{
mutex_lock (semaphore->mutex);
semaphore->value--;

if (semaphore->value < 0) {
do {
cond_wait (semaphore->cond, semaphore->mutex);
} while (semaphore->wakeups < 1);
semaphore->wakeups--;
}
mutex_unlock (semaphore->mutex);
}

void sem_signal (Semaphore *semaphore)
{
mutex_lock (semaphore->mutex);
semaphore->value++;

if (semaphore->value <= 0) {
semaphore->wakeups++;
cond_signal (semaphore->cond);
}
mutex_unlock (semaphore->mutex);
}

最佳答案

看看是否有帮助

From Book Begining Linux programming a counting semaphore that takes a wider range of values. Normally,semaphores are used to protect a piece of code so that only one thread of execution can run it at any one time. For this job a binary semaphore is needed. Occasionally, you want to permit a limited number of threads to execute a given piece of code; for this you would use a counting semaphore

关于c - 用互斥锁重新创建 sem_wait()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14138483/

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