pthread函数采用void*参数.如何发送普通结构而不是指针?
我想将非指针结构发送到一个pthread函数.
另外我想发送一个指向void*函数的指针,这是怎么做到的?可以将任何指针发送到void*函数吗?
不可能; 你必须发一个指针.但是,一个void *可以指向任何东西.如果你的struct变量被调用foo,你可以简单地传递它(void *) &foo,并且在函数内部,你可以将它强制转换为例如struct Foowith struct Foo * fooPtr = (struct Foo *) param;或struct Foo foo = *((struct Foo *) param);.
编辑:作为注释中提到的@forsvarir,foo 不能是局部变量(除非调用函数等待线程完成).请参阅@Gavin Lock的帖子.
根据您的意见,您需要做这样的事情......
在您的主要代码中:
void PassSomeStuff(struct TheStruct myStruct) {
struct TheStruct *pStruct = malloc(sizeof(struct TheStruct));
memcpy(pStruct, &myStruct, sizeof(struct TheStruct));
/* Start the watchdog thread passing in the structure */
pthread_create(/* other args */, &myWatchDogThreadFunc, pStruct); */
}
Run Code Online (Sandbox Code Playgroud)
在你的看门狗线程中:
void *myWatchDogThreadFunc(void *pArgs) {
struct TheStruct *pStruct = (struct TheStruct *)pArgs;
/* use the struct */
/* Pass Ownership to the navigation thread*/
/* Start the navigation thread passing in the structure */
pthread_create(/* other args */, &myNavigationThreadFunc, pStruct);
}
Run Code Online (Sandbox Code Playgroud)
在导航线程中:
void *myNavigationThreadFunc(void *pArgs) {
struct TheStruct *pStruct = (struct TheStruct *)pArgs;
/* use the struct */
/* cleanup */
free(pStruct); /* or pass it to somebody else... */
}
Run Code Online (Sandbox Code Playgroud)
你不能只做:
void PassSomeStuff(struct TheStruct myStruct) {
pthread_create(/* other args */, &myStruct);
}
Run Code Online (Sandbox Code Playgroud)
因为myStruct将得到清理...当PassSomeStuff回报.获取地址(获取指针),不会复制对象.
注意: