【问题标题】:Correct form of lightswitch semaphore in CC中电灯开关信号量的正确形式
【发布时间】:2017-05-10 14:18:22
【问题描述】:

在非面向对象的 C 语言中,lightswitch 信号量的正确替代形式应该如何?灯开关信号量的 Python 参考写在本文Little Book Of Semaphores 中。

灯开关代码:

class Lightswitch :

  def __init__(self):
    self.counter = 0
    self.mutex = Semaphore(1)

  def lock(self, semaphore):
    self.mutex.wait()
      self.counter += 1
      if self.counter == 1:
        semaphore.wait()
    self.mutex.signal()

  def unlock(self, semaphore):
    self.mutex.wait()
      self.counter -= 1
      if self.counter == 0:
        semaphore.signal()
    self.mutex.signal()

【问题讨论】:

  • “在非面向对象的 C 语言中,正确的灯开关信号量替代形式应该如何?”只是一种奇特的说法,即“为我编写代码”,它不是这个网站的用途。
  • @csm_dev 没有必要“为我写代码”。你可以指出一些想法我应该怎么做。没关系,反正我做到了。祝你有美好的一天:)

标签: python c semaphore


【解决方案1】:

其中一个解决方案可能如下所示:

typedef struct 
{
    int counter;
    sem_t mutex;

}LightSwitch;

void ls_lock(LightSwitch *ls, sem_t *sem){
    sem_wait(&ls->mutex);
    ls->counter++;
    if (ls->counter == 1)
    {
        sem_wait(sem);
    }
    sem_post(&ls->mutex);
}

void ls_unlock(LightSwitch *ls, sem_t* sem){
    sem_wait(&ls->mutex);
    ls->counter--;
    if (ls->counter == 0)
    {
         sem_post(sem);
    }
    sem_post(&ls->mut);
}

【讨论】:

    猜你喜欢
    • 2018-09-09
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多