Function pointer to member functions

R

Rookie

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();
}
 
L

Lev Walkin

Rookie said:
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.

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.
 
P

Paul Pluzhnikov

Lev Walkin said:
pthread_create(&threadId1, 0, (void (*)(void))this->funcA, this);

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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top