Running background process in c++ using pthread

1.4k Views Asked by At

I am developing an API in c++ to be used in iOS and Android development. Hence, I need to use pthread.

Now I have a function, which sends data to the server after serialization of a queue.

//include headers here
 void sendToServer(queue q) {
  /*
  send the whole queue to server after serialization
  pop the queue
  */
}

which is called by

// headers
void log (data)
{
  while(1)
  {/*
  add data to queue q
  */
  if(num_nodes>=threshold || duration > interval)
  sendToServer(q);
  //apply thread wait condition 
  }
}

If i want to make a separate thread for log which runs in the background, can I implement a singleton class with a method get_instance which starts a thread with log

class C
{
  private:

    C();
    /*disallow copy constructor and assignment operator*/
    static C* singleton_inst;
    pthread_t t;
    void sendToServer(queue q);

  public:

    void* log(void*);
    static C* get_instance()
    {
      if(singleton_inst==NULL)
      {
        pthread_create(t, NULL, log, NULL);
        singleton_inst= new C();
      }
      return singleton_inst;
    }
}

So, next time in my test function, when i do:

C::get_instance(); //C::get_instance->signal_thread_to_resume;

will the second line resume the same thread started in the first line?

1

There are 1 best solutions below

4
On

If you really have to use pthread I think this will work, but it is untested:

#include <iostream>
#include <pthread.h>
using namespace std;

//include headers here
/*the called function must be void* (void*)  */ 
/* so you have to cast queue*/
 void* sendToServer(void* q) {
  /*
  send the whole queue to server after serialization
  pop the queue
  */
}

pthread_t thread1;

// headers
void log (char* data)
{

  // create the thread
  int th1 = pthread_create( &thread1, NULL, sendToServer, (void*) data);
}

int main() {
  log((char*)"test");
  /* Wait till threads are complete before main continues. Unless we  */
  /* wait we run the risk of executing an exit which will terminate   */
  /* the process and all threads before the threads have completed.   */
  pthread_join( thread1, NULL);
  return 0;
}

Don't forget to link with the pthread libary. Without it, it will not work.
But try to use std::thread.