Search code examples
c++linuxmultithreadingboostboost-thread

Boost thread not calling thread function


I am trying to create a boost thread and I see the thread is created but the control does not come to the thread function. Can someone please explain why is it so?

Please see below for the code used.

header_file.h

class fa {
public:
  fa();
  ~fa();
  int init(void);
  static void* clThreadMemFunc(void *arg) { return ((fa*)arg)->collectData((fa*)arg); }
  void* collectData(fa *f );
private:
  int m_data;
  boost::thread *m_CollectDataThread;
};

`

test.cpp

int fa::init(void)
{
     if (m_CollectDataThread== NULL)
     {
          printf("New Thread...\n");
          try 
          {
              m_CollectDataThread = 
              new boost::thread((boost::bind(&fanotify::clThreadMemFunc, this)));
          }
          catch (...){perror("Thread error ");}
          printf("m_CollectDataThread: %p \n", m_CollectDataThread);
     }
 return 0;
}
void* fa::collectData(fa *f)
{
    printf("In collectData\n");
    int data = f->m_data;
    printf("data %d",data);
}

The test.cpp is complied/built as a library (test.so) and another main function calls the init function. I see the variable m_collectDataThread value changing from null to some value (thread gets created) and also catch does not get any exception.

But I don't see any statement in collectData getting printed. Why is the thread not able to reach it?


Solution

  • Perhaps try adding a join.

    E.g.

     try 
          {
              m_CollectDataThread = 
              new boost::thread(boost::bind(&fanotify::clThreadMemFunc, this));
               m_CollectDataThread->join();    
          }