类成员函数的地址
我有一个名为 CSum 的类,其中包含一个静态方法,其标识符为:
static double fileProc(string myFile);
在我的主函数中,我将简单地调用它
CSum::fileproc("foo.txt")
但是,我想在两个单独的文件上调用 pthreads。因此我需要获取这个方法的地址。我这样做
return1 = pthread_create(&t1, NULL, &CSum::fileProc(file1), NULL);
return2 = pthread_create(&t2, NULL, &CSum::fileProc(file2), NULL);
但我收到一个错误
左值需要作为一元“&”操作数。
有什么建议吗?
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. Therefore 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不传递参数,只需给出函数的名称。您希望它获取的参数是 pthread_create 的下一个参数。
而不是
适当地执行
Cast 类型。请注意,线程函数应该接受指针作为参数,请确保正确定义它。
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
do
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)
是一个调用函数的表达式,并为您提供函数返回的值作为表达式的值。您试图获取该值的地址,但您不能这样做,并且这不会执行您想要的操作。&CSum::fileProc
将为您提供函数指针,但它没有用于 pthread 的正确签名。由于 pthreads 是一个 C 库,因此它具有非常简单的接口。对于 C++ 来说,最好的选择是使用更高级别的 C++ 库,该库在底层使用 pthreads(至少在 unix 上),例如 boost 线程。如果由于某种原因你不能这样做,你需要编写自己的包装器。要在单独的线程中调用函数,您需要编写类似以下内容的内容:
并使用 调用它
这只会给您调用,注意,结果会被这段代码丢弃。如果你想用 pthread_join 收集结果,你必须做更多的工作。
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:
and call it with
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.