On 16 July 2011 08:00, Claudio La Rosa wrote: > > 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. Are you sure you get a segfault? You should get an exception in the myAsyncFun thread, which is not caught so the program calls std::teminate You can't use a promise more than once, so your loop will always fail on the second iteration. Also, as matters of style, you don't need to create the std::thread using 'new' but if you do then you should delete it.