charis
charis

Reputation: 439

How to pass pointers to class methods to a boost thread

I have recently started experimenting with boost::thread and i would like to implement a data logger that prints the return values of some class methods on a regular basis (1/sec) in a separate thread.

The Data class has two private variables dataRx and dataTx and two getters that expose these values.

Data.h:

class Data
{
public:
  Data();
  virtual unsigned long GetDataTx();
  virtual unsigned long GetDataRx();

private:
  unsigned long fDataTx;
  unsigned long fDataRx;
};

Data.cpp:

#include "Data.h"

Data::Data() : fDataTx(5), fDataRx(10)
{
}

unsigned long Data::GetDataTx()
{
  return fDataTx;
}

unsigned long Data::GetDataRx()
{
  return fDataRx;
}

And the main function:

#include <iostream>
#include <unistd.h>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include "Data.h"

using namespace std;

void Log(void *objPtr1, void *objPtr2)
{
  while(1) {
    cout << objPtr1->GetDataTx() << " " << objPtr2->GetDataTx() <<  endl;
    sleep(1);
  }
}

int main(int argc, char** argv)
{
  Data obj1;
  Data obj2;

  boost::thread logThread(Log, &obj1, &obj2);
}

But i get this error:

main.cpp: In function ‘void Log(void*, void*)’:
main.cpp:14:20: error: ‘void*’ is not a pointer-to-object type
     cout << objPtr1->GetDataTx() << " " << objPtr2->GetDataTx() <<  endl;
                    ^
main.cpp:14:51: error: ‘void*’ is not a pointer-to-object type
     cout << objPtr1->GetDataTx() << " " << objPtr2->GetDataTx() <<  endl;
                                                   ^

So obviously this is not the correct way to pass the pointers to the threads. Any suggestions?

Upvotes: 0

Views: 585

Answers (1)

ForEveR
ForEveR

Reputation: 55887

It's correct way to pass pointer to thread. One question: why your log function receives void pointers, instead Data pointers? If you should use void pointers, you should cast them to Data* in function.

void Log(void *objPtr1, void *objPtr2)
{
  Data* ptr1 = static_cast<Data*>(objPtr1), ptr2 = static_cast<Data*>(objPtr2);
  while(1) {
    cout << objPtr1->GetDataTx() << " " << objPtr2->GetDataTx() <<  endl;
    sleep(1);
  }
}

Upvotes: 1

Related Questions