CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Threaded View

  1. #1
    Join Date
    Jan 2012
    Location
    USA
    Posts
    91

    [RESOLVED] Two-way event-driven communication between objects (similar to producer-consumer)

    Hi,

    I need to implement a two-way asynchronous communication between two objects, not using any IPC.

    What I have now is a producer-consumer model where producer sends a number "88" to consumer at random intervals. Now, I need consumer to send a number "99" back to producer at a random intervals, this probably should be done in a separate thread. My prototype could be totally wrong for what I need hence I am open to any suggestions. I'd appreciate any help, thank you.

    I am using GNU on Linux, here is the compile line.
    Code:
    g++ -g -std=c++11 main.cpp -o main
    Code:
    #include<iostream>
    #include<chrono>
    #include<thread>
    
    class IObject
    {
    	public:
    	virtual void fromApp(int i) = 0;
     	virtual int toApp(int& i) = 0;			// ???
    };
    
    class Producer
    {
    	private:
    	IObject& obj;
    
    	public:
    	Producer(IObject& p) : obj(p) { }
    	void run() { while(1) {int d=rand()%500+100; std::this_thread::sleep_for(std::chrono::milliseconds(d)); obj.fromApp(88);} }	// Generate and send data.
    };
    
    class Consumer : public IObject
    {
    	public:
    	void fromApp(int i) { std::cout << i*10 << std::endl; }		// Process data.
    	int toApp(int& i) {while(1) {int d=rand()%500+100; std::this_thread::sleep_for(std::chrono::milliseconds(d)); i = 99;} }
    };
    
    int main()
    {
    	Consumer cons;
    	Producer prod(cons);
    	prod.run();
    }
    Last edited by vincegata; October 27th, 2013 at 11:09 AM. Reason: rephrased

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured