2017-05-10 32 views
-6

灯光开关信号的正确替代形式应该如何在非面向对象的C语言中看起来像? lightswitch信号灯的Python参考文件写在这份文件Little Book Of Semaphores中。C中的灯光开关信号的正确形式

的LightSwitch代码:

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() 
+0

“_How应的LightSwitch的正确的替代形式旗语看起来像面向C语言的非对象_ “只是说”为我编写代码“的奇特方式,这不是本网站的目的。 – csmckelvey

+0

@csm_dev没有必要“为我写代码”。你可以指出一些想法,我应该怎么做。没关系,我反正做了。祝你今天愉快 :) – Amphoru

回答

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