简体   繁体   English

使用pthreds与C ++中的线程通信

[英]Thread communication with in C++ using pthreds

There are two threads T1 and T2 有两个线程T1和T2

class Sender{
      public:
      void sendMessage(); 
};

class Reciever{
      public:
      void getMessage(string msg); 
};

Consider Sender S is in Thread T1, Reciever R is in Thread T2 and now I need S.sendMessage() should communicate with object R to execute getMessage(string msg). 考虑发送方S在线程T1中,接收方R在线程T2中,现在我需要S.sendMessage()应该与对象R通信以执行getMessage(string msg)。 So how can I do it... Producer and consumer approach might help but here it is a one-time requirement so is that really neede to maintain a common queue? 所以我该怎么做...生产者和消费者方法可能会有所帮助,但这是一项一次性要求,因此真的需要维护一个公共队列吗? please help me. 请帮我。

Condition variables are what you are looking for. 条件变量是您要寻找的。 They allow a thread to wait (blocking) for an event sent from another thread. 它们允许线程等待(阻塞)另一个线程发送的事件。

You correctly discerned that you do not need a producer-consumer queue if there is only one producer and only one consumer and only a single message is passed. 您正确地识别出,如果只有一个生产者和一个消费者,并且仅传递一条消息,则不需要生产者-消费者队列。

So, your receiver thread calls getMessage (which should either return a string, or take the string as a reference parameter), which internally waits for a condition variable. 因此,您的接收器线程调用getMessage(它应该返回一个字符串,或者将字符串作为参考参数),该方法在内部等待条件变量。 Then, in the sender thread, you notify the condition variable inside sendMessage. 然后,在发送方线程中,通知sendMessage内部的条件变量。 This wakes up the receiver thread. 这将唤醒接收器线程。

Edit : Although you are asking a pthread-specific question, pthread has an equivalent of C++'s std::condition_variable. 编辑 :尽管您正在询问特定于pthread的问题,但是pthread具有C ++的std :: condition_variable的等效项。 I recommend you use C++11's utilities instead of talking to pthreads directly, as they are easier to use. 我建议您使用C ++ 11的实用程序,而不是直接与pthread对话,因为它们更易于使用。

Edit 2 : You cannot just make another thread execute some function. 编辑2 :您不能仅仅让另一个线程执行某些功能。 The only thing you can do between threads is communication, so if you want to have some reaction in another thread to something you do in your thread, the other thread has to be actively waiting for you to trigger this event (by notifying a condition variable or similar). 线程之间唯一可以做的就是通信,因此,如果您希望另一个线程对您在该线程中所做的事情有反应,则另一个线程必须积极地等待您触发此事件(通过通知条件变量)或类似)。

The standard way combines a std::queue with a mutex and a condition variable. 标准方法将std::queue与互斥量和条件变量结合在一起。 The mutex is used by the condition variable and protects the queue. 互斥锁由条件变量使用,并保护队列。 The receiver waits until the queue is not empty and then pops the message from the queue. 接收者等待直到队列不为空,然后从队列中弹出消息。 The sender pushes the message onto the queue. 发件人将消息推送到队列中。

When only one type of message is needed, you can use a queue of messages, if not then make it dynamic by sending shared pointers to messages. 如果只需要一种消息,则可以使用消息队列,如果不需要,则可以通过发送消息的共享指针使其动态化。

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

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