linux系统c语言setevent函数,c# – Linux下的AutoResetEvent的C等价物是什么?

AutoResetEvent最类似于二进制信号量.人们说“条件变量”本身并没有错,但条件变量在类似的情况下使用,而不是类似的对象.您可以在条件变量之上实现(未命名)AutoResetEvent:

#include

#include

class AutoResetEvent

{

public:

explicit AutoResetEvent(bool initial = false);

~AutoResetEvent();

void Set();

void Reset();

bool WaitOne();

private:

AutoResetEvent(const AutoResetEvent&);

AutoResetEvent& operator=(const AutoResetEvent&); // non-copyable

bool flag_;

pthread_mutex_t protect_;

pthread_cond_t signal_;

};

AutoResetEvent::AutoResetEvent(bool initial)

: flag_(initial)

{

pthread_mutex_init(&protect_, NULL);

pthread_cond_init(&signal_, NULL);

}

void AutoResetEvent::Set()

{

pthread_mutex_lock(&protect_);

flag_ = true;

pthread_mutex_unlock(&protect_);

pthread_cond_signal(&signal_);

}

void AutoResetEvent::Reset()

{

pthread_mutex_lock(&protect_);

flag_ = false;

pthread_mutex_unlock(&protect_);

}

bool AutoResetEvent::WaitOne()

{

pthread_mutex_lock(&protect_);

while( !flag_ ) // prevent spurious wakeups from doing harm

pthread_cond_wait(&signal_, &protect_);

flag_ = false; // waiting resets the flag

pthread_mutex_unlock(&protect_);

return true;

}

AutoResetEvent::~AutoResetEvent()

{

pthread_mutex_destroy(&protect_);

pthread_cond_destroy(&signal_);

}

AutoResetEvent event;

void *otherthread(void *)

{

event.WaitOne();

printf("Hello from other thread!\n");

return NULL;

}

int main()

{

pthread_t h;

pthread_create(&h, NULL, &otherthread, NULL);

printf("Hello from the first thread\n");

event.Set();

pthread_join(h, NULL);

return 0;

}

但是,如果您需要命名自动重置事件,则可能需要查看信号量,并且可能需要稍微更难以翻译代码.无论哪种方式,我都会仔细查看平台上pthreads的文档,条件变量和自动重置事件不一样,并且行为不一样.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值