This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

C++0x, thread, promise and future


Hello!


I am making a simple template class for communication with two thread in
C++0x, using the promise and future.
My class make a channel to communicate thread with the main program and
another channel to allow the child thread to initiate communication with the
parent thread (or main program).

This is the code:

#include 
#include 
#include 

using namespace std;

template
class ThreadChannel
{
    private:
     std::promise ch1_Promise;
     std::future  ch1_Future;

     std::promise ch2_Promise;
     std::future  ch2_Future;

    public:
        ThreadChannel();
        virtual ~ThreadChannel();

         T1 recvFromFather(void);
         void sendToChild(T1);
         //canale 1
         void sendToFather(T);
         T recvFromChild(void);

};


//
template
ThreadChannel::ThreadChannel()
{
 ch1_Future = ch1_Promise.get_future();
 ch2_Future = ch2_Promise.get_future();
}

template
ThreadChannel::~ThreadChannel()
{
  //cout<<"Sono nel distruttore!!"<
T ThreadChannel::recvFromChild()
{
  return ch1_Future.get();
}

template
void ThreadChannel::sendToFather(T data)
{
  return ch1_Promise.set_value(data);
}

template
void ThreadChannel::sendToChild(T1 data)
{
  return ch2_Promise.set_value(data);
}

template
T1 ThreadChannel::recvFromFather()
{
  return ch2_Future.get();
}



I use this class in my main:



int main()
{
    ThreadChannel* myChannel=new ThreadChannel();
    // thread
    std::thread* t = new std::thread(myAsyncFun,myChannel);
    int myVar = 33;
    myChannel->sendToChild(myVar);
    int resp = myChannel->recvFromChild();
    cout<<"Response from thread: "<join();
    delete myChannel;

    return 0;
}


My Thread code:

void myAsyncFun(ThreadChannel* ch)
{
    while(1)
    {
     int r = ch->recvFromFather();
     ch->sendToFather(++r);
    }
}


Ok...this code work, but... the first time the while loop executesn(in
myAsyncFun), it works well.
but the second time, when for the second time the statement is executed:

int r = ch-> recvFromFather ();

I have a segmentation fault.

Why?
-- 
View this message in context: http://old.nabble.com/C%2B%2B0x%2C-thread%2C-promise-and-future-tp32069856p32069856.html
Sent from the gcc - libstdc++ mailing list archive at Nabble.com.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]