It is currently Tue, 30 Nov 2021 17:55:13 GMT



 
Author Message
 Function pointer to member functions
Hi,

I was writing a simple multi-threaded program (code below). My intent is to
invoke a member function of a class that creates two threads - each thread
executes another member function of the same class. The pthread_create
function used to create a thread requires a pointer to the function that
will be executed. I tried all the possible syntax ideas that came to mind,
but I am not able to pass it a pointer to the member function of the class.
Can someone please point out my error. Thanks.

class test
{
public:
 void* funcA(void* dud)
 {
  int i=0;
  char c,*d;
  d=(char*)dud;
  c=*d;
  for(i=0;i<100;i++)
   printf("%c",c);
 }

 int funcB()
 {
  pthread_t threadId1,threadId2;
  char c,d;
  c='a';
  pthread_create(&threadId1,NULL,this->funcA,&c); //I keep getting
compilation errors for this line. I tried a::funcA, &a::funcA, funcA,
&funcA. None of them work.
  d='b';
  pthread_create(&threadId2,NULL,this->funcA,&d); //I keep getting
compilation errors for this line
  pthread_join(threadId2,NULL);
  pthread_join(threadId1,NULL);
  perror("say what");
 }

main()
{
 test obj;
 obj.funcB();



 Sat, 31 Mar 2007 07:40:19 GMT   
 Function pointer to member functions

Your main problem is cross-posting.

The second problem is that a funcA has a hidden "this" pointer, which is not
passed through for you by pthread_create(). Use a "friend" wrapper, or declare
the funcA as void*funcA(void) and have the "this" pointer passed explicitly:

        pthread_create(&threadId1, 0, (void (*)(void))this->funcA, this);

You'll lose the ability to pass &c or &d pointer, though.

--
Lev Walkin
v...@lionet.info



 Sat, 31 Mar 2007 08:15:26 GMT   
 Function pointer to member functions

The result of doing the above is still undefined.

POSIX requires that an 'extern "C"' linkage function be passed to
pthread_create().

This has been discussed many times and at length in com.programming.threads

Cheers,
--
In order to understand recursion you must first understand recursion.
Remove /-nsp/ for email.



 Sat, 31 Mar 2007 11:58:50 GMT   
 
   [ 3 post ] 

Similar Threads

1. C++ compiler 5.3 can't compile RW vector of member function pointers

2. Pointer to Member functions (C++ problem)

3. aCC compiler error with member function pointers on HPUX

4. C++ class member function as a thread function.

5. function calls versus function pointers ?

6. About function that returns function pointer

7. function, function...who's got the function?

8. pthread_create & C++ member function problem

9. Problem w/virtual member functions using g++ 2.8.1 on Solaris 2.5.1


 
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group.
Designed by ST Software