简体   繁体   English

如何创建结构并通过pthread_create()传递到新线程

[英]how to create a struct and pass to a new thread via pthread_create()

I have a callback function I am writing where I need to: 我在需要写的地方有一个回调函数:

1 create a struct 1创建一个结构
2 create a new thread and pass this struct to the thread for it's exclusive use 2创建一个新线程并将此结构传递给该线程以供其专用
3 return a pointer to this struct ... from the callback function ... to the main program. 3从该回调函数...返回指向该结构的指针...到主程序。

This will allow communications through shared memory between the original program and the new threads. 这将允许通过原始程序和新线程之间的共享内存进行通信。

I assume I have to use malloc since the scope of a struct created in the callback function is only in the function. 我假设我必须使用malloc,因为在回调函数中创建的结构的作用域仅在该函数中。

I can't make it static because I will create multiple threads each with their own personal struct. 我不能使其成为静态,因为我将创建多个线程,每个线程都具有自己的个人结构。

I need to understand the process since I am a newbie. 因为我是新手,所以我需要了解该过程。

Would it work this way? 这样行吗?

1 malloc a chunk of memory "sizeof" the struct. 1 malloc分配一块内存“ sizeof”该结构。
2 pass the pointer to this chunk to the new thread and return it to the main program. 2将指向该块的指针传递给新线程,并将其返回到主程序。
3 once in the new thread make a new struct using this memory? 3在新线程中一次使用此内存创建新结构吗?

I have searched for a week now and can't see how this should be done. 我已经搜索了一个星期,看不到应该怎么做。

BTW: I cannot modify the main program which is single threaded by design. 顺便说一句:我不能修改设计单线程的主程序。 I can only make this callback function to spawn one of many new threads and communicate thru this shared memory which I would like to be a struct. 我只能使该回调函数产生许多新线程之一,并通过该共享内存(我想成为一个结构)进行通信。

Thanks. 谢谢。

struct myStruct
{
    int elem1;
    int elem2;
    int elem3;
};



int* callBack(some parameters)
{
    *p = malloc(sizeof(myStruct));

    result = pthead_create( ??, ??, void *(*newThread), *p);

    return p;
}


void newThread()
{
    // pull off *p from stack?

    // somehow use the declared struct to access the malloc mem

    p->elem1 = p->elem2 + p->elem3;
}

Threads created through pthread_create() take in a void* as their argument, so the prototype of your thread routine should be as follows: 通过pthread_create()创建的线程将void*作为其参数,因此线程例程的原型应如下所示:

void newThread(void* data)

This void* then corresponds to the pointer passed as the final argument to pthread_create . 然后,该void*对应于作为最终参数传递给pthread_create的指针。 You can then cast this pointer to the appropriate data type (but make sure you get the right one!). 然后,您可以将此指针转换为适当的数据类型(但请确保获得正确的数据类型!)。 An example is as follows: 示例如下:

void newThread(void* data)
{
    struct myStruct* p = data;
    p->elem1 = p->elem2 + p->elem3;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM