C++0x, thread, promise and future
Claudio La Rosa
clros@tiscali.it
Sat Jul 16 07:00:00 GMT 2011
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 <iostream>
#include <future>
#include <thread>
using namespace std;
template<typename T = std::string,typename T1 = std::string>
class ThreadChannel
{
private:
std::promise<T> ch1_Promise;
std::future<T> ch1_Future;
std::promise<T1> ch2_Promise;
std::future<T1> ch2_Future;
public:
ThreadChannel();
virtual ~ThreadChannel();
T1 recvFromFather(void);
void sendToChild(T1);
//canale 1
void sendToFather(T);
T recvFromChild(void);
};
//
template<typename T,typename T1>
ThreadChannel<T,T1>::ThreadChannel()
{
ch1_Future = ch1_Promise.get_future();
ch2_Future = ch2_Promise.get_future();
}
template<typename T,typename T1>
ThreadChannel<T,T1>::~ThreadChannel()
{
//cout<<"Sono nel distruttore!!"<<endl;
}
template<typename T,typename T1>
T ThreadChannel<T,T1>::recvFromChild()
{
return ch1_Future.get();
}
template<typename T,typename T1>
void ThreadChannel<T,T1>::sendToFather(T data)
{
return ch1_Promise.set_value(data);
}
template<typename T,typename T1>
void ThreadChannel<T,T1>::sendToChild(T1 data)
{
return ch2_Promise.set_value(data);
}
template<typename T,typename T1>
T1 ThreadChannel<T,T1>::recvFromFather()
{
return ch2_Future.get();
}
void myAsyncFun(ThreadChannel<int,int>* ch)
{
while(1)
{
int r = ch->recvFromFather();
ch->sendToFather(++r);
}
}
int main()
{
ThreadChannel<int,int>* myChannel=new ThreadChannel<int,int>();
// thread
std::thread* t = new std::thread(myAsyncFun,myChannel);
int myVar = 33;
myChannel->sendToChild(myVar);
int resp = myChannel->recvFromChild();
cout<<"Response from thread: "<<resp<<endl;
t->join();
delete myChannel;
return 0;
}
The first time the while loop executes (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?
(I use GCC 4.5.2 on Linux Ubuntu and libpthread 2.13)
--
View this message in context: http://old.nabble.com/C%2B%2B0x%2C-thread%2C-promise-and-future-tp32072781p32072781.html
Sent from the gcc - Help mailing list archive at Nabble.com.
More information about the Gcc-help
mailing list