将正常数据传递给pthread void*

jar*_*ryd 8 c pthreads

pthread函数采用void*参数.如何发送普通结构而不是指针?

我想将非指针结构发送到一个pthread函数.

另外我想发送一个指向void*函数的指针,这是怎么做到的?可以将任何指针发送到void*函数吗?

Aas*_*set 8

不可能; 你必须发一个指针.但是,一个void *可以指向任何东西.如果你的struct变量被调用foo,你可以简单地传递它(void *) &foo,并且在函数内部,你可以将它强制转换为例如struct Foowith struct Foo * fooPtr = (struct Foo *) param;struct Foo foo = *((struct Foo *) param);.

编辑:作为注释中提到的@forsvarir,foo 不能是局部变量(除非调用函数等待线程完成).请参阅@Gavin Lock的帖子.


for*_*rir 7

根据您的意见,您需要做这样的事情......

在您的主要代码中:

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回报.获取地址(获取指针),不会复制对象.

注意:

  • 只要您确定所有线程都已完成,您的任何线程都可以通过调用free来清理结构.
  • 所有线程(主,看门狗,导航)都引用了相同的结构实例(因此,如果它们正在更改其内容,您可能需要通过锁定来保护它).如果这不是预期的效果,那么您需要在每一步创建(malloc)结构的新副本,以便每个线程都拥有它自己的值副本.