面向对象的信号量在C ++中的使用 [英] Object-oriented semaphore usage in C++

查看:235
本文介绍了面向对象的信号量在C ++中的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在C中使用Unix信号量。在使用它们之前,我必须调用名为 sem_init 的构造函数ish函数,使用它们后,我必须调用析构函数 - 类似于 sem_destroy 的函数。



我知道我可以继续这样做在C + +,因为它向后兼容C,但是C ++有一个真正的面向对象的方式来使用信号量?

解决方案

如果你真的坚持使用POSIX信号量, ,你当然可以在类中包装 sem_t

  {
sem_t sem;

public:
Semaphore(int shared,unsigned value)
{sem_init(& sem,shared,value); }

〜Semaphore(){sem_destroy(& sem); }

int wait(){return sem_wait(& sem); }
int try_wait(){return sem_trywait(& sem); }
int unlock(){return sem_post(& sem); }
};

练习读者:您可能想添加异常而不是C风格的错误代码,特征。此外,这个类应该是不可复制的。最简单的方法是继承 boost :: noncopyable ;)



>:如@Ringding说的,循环 EINTR 将是一个很明智的事情。

  int Semaphore :: wait()
{
int r;
do {
r = sem_wait(& sem);
} while(r == -1&& errno = EINTR);
return r;
}


I know how to use Unix semaphores in C. Before using them I must call a constructor-ish function named sem_init and after using them I have to call a destructor-like function named sem_destroy.

I know I can keep doing this in C++ because of its backwards compatibility with C, but does C++ have a real object-oriented way to use semaphores?

解决方案

If you really insist on using POSIX semaphores and not Boost, you can of course wrap sem_t in a class:

class Semaphore {
    sem_t sem;

  public:
    Semaphore(int shared, unsigned value)
    { sem_init(&sem, shared, value); }

    ~Semaphore() { sem_destroy(&sem); }

    int wait() { return sem_wait(&sem); }
    int try_wait() { return sem_trywait(&sem); }
    int unlock() { return sem_post(&sem); }
};

Exercise for the reader: You may want to add exceptions instead of C-style error codes and perhaps other features. Also, this class should be noncopyable. The easiest way to achieve that is inheriting from boost::noncopyable ;)

Edit: as @Ringding remarks, looping on EINTR would be a very wise thing to do.

int Semaphore::wait()
{
    int r;
    do {
        r = sem_wait(&sem);
    } while (r == -1 && errno == EINTR);
    return r;
}

这篇关于面向对象的信号量在C ++中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆