Multithreading for callback function in C++

2.2k views Asked by At

Im implementing a chat application using Jabber/XMPP and gloox framework which should send and receive messages concurrently in Ubuntu Linux.

My current code implementation is :

int main()
{
        ...
 int temp = pthread_create(&iSend, NULL, SendMessage, &b);
 int temp1 = pthread_create(&iRecv, NULL, ConnServer, &b);
}

void* ConnServer(void *athis)
{
 UserClient *t = (UserClient*)athis;
 t->ConnecttosServer();
}

bool UserClient::ConnecttosServer()
{
 //JID jid( "[email protected]/gloox" );

 j = new Client( iUserJid, iUser.getPassword() );
 j->registerMessageHandler( this);
 j->registerConnectionListener( this );
 j->registerMessageSessionHandler(this);
 bool result = j->connect(false);
 if(result == true)
 {
  iConnected = true;
  ConnectionError er = ConnNoError;
  ConnectionError er1 = ConnNoError;
  while(er == ConnNoError || er1 == ConnNoError)
  {
   er = j->recv(500000);
   sleep(2);
  }
  delete j;
 }
...
}

void* SendMessage(void * athis )// JID *aDest)
{
 UserClient *t = (UserClient*)athis;
 //JID *t = (JID)dest;

 string ip ;
 cout << "enter here";
 cin >> ip;
 if(t->iConnected == true)
 {
  if(t->iMessageSession == NULL )
  {
   string aBody = "hello";

   MessageSession *session = new MessageSession(t->j, t->iDestJid);
   session->registerMessageHandler(t);
   session->send(aBody.c_str());
  } 
 }
}

The problem faced is both the threads are created and pthread_join( ) is called for both.

The iSend thread is scheduled first but gets suspended at cin. Once the recv( ) function is called, which runs in iRecv thread, the recv call back function handleMessage( ) is called. However the control never shifts back to the iSend thread which should call SendMessage( ) function.

Please help

2

There are 2 answers

1
CashCow On

I cannot see in there how SendMessage ever sends more than one "hello" message.

There are various memory issues here of course, eg j won't get deleted at all if connect failed, and as its scope is function-only there is no real need to create it with new at all.

0
Mike Lyons On

You cannot count on the iSend thread being scheduled first. That is completely up to the operating system.