Address of a class member function
I have a class called CSum which contains a static method who's identifier is:
static double fileProc(string myFile);
In my main function I would simply call it by
CSum::fileproc("foo.txt")
However, I will like to invoke pthreads on two separate files. Theref开发者_开发技巧ore I need to obtain the address of this method. I do so by
return1 = pthread_create(&t1, NULL, &CSum::fileProc(file1), NULL);
return2 = pthread_create(&t2, NULL, &CSum::fileProc(file2), NULL);
But I get an error
lvalue required as a unary '&' operand.
Any suggestions?
You don't pass parameters, you just give the name of the function. The parameter you want it to get is the next parameter of the pthread_create
.
Instead of
pthread_create(&t2, NULL, &CSum::fileProc(file2), NULL);
do
pthread_create(&t2, NULL, &CSum::fileProc, file2);
Cast types as appropriate. Note that the thread function is supposed to accept a pointer as a parameter, make sure you define it appropriately.
CSum::fileProc(file1)
is an expression that calls the function and gives you the value the function returns as the value of the expression. You are trying to take the address of that value, which you can't, and this won't do what you want.
&CSum::fileProc
will give you the function pointer, but it does not have the correct signature for use with pthreads. Since pthreads is a C library, it has a very simplistic interface. Your best bet for C++ is to use a higher-level C++ library that uses pthreads underneath (at least on unixes), like boost threads.
If for some reason yoou can't do that, you need to write your own wrappers. To call your function in a separate thread, you would need to write something like:
class CSum {
...
static void fileProcWrapper(void* param) {
const char* fileName = (const char*) param;
fileProc(fileName);
}
...
and call it with
pthread_create((&t2, NULL, &CSum::fileProc, (void*) file1.c_str());
That just gives you the call, mind, the result is thrown away with this code. If you want to collect the result with pthread_join, you have to do a bit more work.
精彩评论