简体   繁体   English

Posix线程通信Linux

[英]Posix thread communication Linux

I have a worker thread which is alive from the start of the programme and would consistently take an object from a queue to process. 我有一个工作线程,该线程从程序开始就处于活动状态,并且始终将一个对象从队列中移出进行处理。 I am wondering what is the best way to block the thread? 我想知道阻止线程的最佳方法是什么? The object would be pushed into the queue at about magnitude of every tens of microseconds( between 10 - 100 micro seconds). 该对象将以大约每几十微秒的幅度(10-100微秒之间)被推入队列。 Should I set the thread to sleep at a constant period or should I work out some signalling mechanism between the threads? 我应该将线程设置为恒定睡眠时间还是应该制定出线程之间的某种信令机制? I would like mainly focusing on the performance issue. 我想主要关注性能问题。 Any ideas? 有任何想法吗?

Thanks. 谢谢。

On the other hand you could use condition variables as long as it is generic feature of pthreads. 另一方面,您可以使用条件变量 ,只要它是pthreads的通用功能即可。 Condition variables is designed upon pthread mutexes so they are very effective sync primitives (depending on the actual platform of course). 条件变量是根据pthread互斥量设计的,因此它们是非常有效的同步原语(当然取决于实际平台)。

Follow them . 跟随他们

Posix message queues looks like a good candidate, if your data is not too big. 如果您的数据不太大, Posix消息队列看起来是一个不错的选择。 You can also use a POSIX semaphore : 您还可以使用POSIX信号量

The producer thread put data on a queue, and do a sem_post 生产者线程将数据放在队列中,然后执行sem_post
The consumer thread wait using sem_wait, and remove data from the queue. 使用者线程使用sem_wait等待,并从队列中删除数据。

It's easier to use IMO than condition variable. 使用IMO比使用条件变量更容易。 Of course you need to protect your queue. 当然,您需要保护您的队列。 Depending on the size of the object, it might be more suited than message queues, but you need to implement your own queue. 根据对象的大小,它可能比消息队列更适合,但是您需要实现自己的队列。

Both can be used between process instead of thread. 两者都可以在进程之间而不是线程之间使用。 Should you decide to use process instead of thread, you could keep your synchronisation mechanism, which is not the case with condition variables. 如果您决定使用进程而不是线程,则可以保留同步机制,条件变量则不是这种情况。

Use POSIX message queues in blocking mode ( mq_open , etc.), which is really simple, and see if they satisfy your performance requirements. 在阻塞模式( mq_open等)下使用POSIX消息队列,这非常简单,并查看它们是否满足您的性能要求。 If not, ask another question :) 如果没有,问另一个问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM