c++ - Initializing a static POSIX semaphore inside a class -


class semaphore {     private:         static sem_t sem_id; } 

in cpp:

sem_init(&semaphore::sem_id, 0, 0); 

obviously , compiler won't let me run code outside of function. it's not type can initialized value. how do it?

you wrap sem_id in own class performs sem_init on default-construction (and sem_destroy on destruction; don't forget that!).

sadly, sem_t not class can't inherit , must instead compose it:

#include <semaphore.h>  class scoped_sem_t { public:     scoped_sem_t() { sem_init(&sem, 0, 0); }    ~scoped_sem_t() { sem_destroy(&sem); }     sem_t& get() { return sem; }  private:    sem_t sem; };  class semaphore { private:    static scoped_sem_t impl;  // use semaphore::impl.get() };  scoped_sem_t semaphore::impl;  // (don't forget this!) 

(n.b. untested guess should work…)
(also, not best example of class design, gives gist.)

otherwise, sadly, there no ways neatly. write sem_init @ start of main instead, careful not reference semaphore::sem_id other static initialiser.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -