【发布时间】:2021-02-09 23:07:58
【问题描述】:
我在使用带有 POSIX 线程的模板函数时遇到了麻烦。
作为编程语言,我使用 C++98,作为线程基础架构,我使用 POSIX 线程 (<pthread.h>)。
我的环境不支持标准线程 (<thread>)
通常,我们可以将参数传递给 pthreads,如下所示:
#include <stdio.h>
#include <pthread.h>
void * hello(void *input) {
printf("%s\n", (char *)input);
pthread_exit(NULL);
}
int main(void) {
pthread_t tid;
pthread_create(&tid, NULL, hello, "hello world");
pthread_join(tid, NULL);
return 0;
}
问题是,如何将模板函数和参数传递给 pthreads?
这里是示例模板函数:
#include <pthread.h>
template<class T>
void *hello(T val){
SampleInterface *interface = &T;
cout << interface->Message<<endl;
}
int main(void) {
pthread_t tid;
SampleClass sClass;
pthread_create(&tid, NULL, hello, sClass);
pthread_join(tid, NULL);
return 0;
}
如果我使用上述用法,我会收到两个错误:
error: no matches converting function 'hello' to type 'void* (*)(void*)'
error: candidates are: template<class T> void* hello(T)
【问题讨论】:
-
替代方案:从
void * (void *)函数内部调用模板化函数。 -
感谢您的评论。你的意思是调用“hello”函数吗?如果是,它不能解决我的问题。最后,我必须将 T 参数传递给这个函数。
-
问题可能源于编译器无法从
pthread_create(&tid, NULL, hello, sClass);推断出T。但重点是没有意义的。pthread_create想要一个函数,该函数接受void指针并返回void指针。给它任何其他东西,你就会试探命运。 -
是的,也许您对“问题可能源于编译器无法推断”评论是正确的。尽管如此,我还是无法理解如何做到这一点:/
-
我不认为我可以正式回答这个问题而不冒帮助您挖一个更深的洞的风险。
hello需要看起来像template<class T> void *hello(void * userp)并且将被称为pthread_create(&tid, NULL, hello<SampleClass>, &sClass);,但这需要hello包含一些类似SampleInterface *interface = (T *)userp;的代码,我不确定这是正确的决定。
标签: c++ multithreading pthreads c++98