简体   繁体   English

pthread我可以得到原始参数吗?

[英]pthread can I get the original argument?

Heres the snippet of code: 以下是代码段:

pthread_create(&worker->thread, NULL, EagleWorker_begin, worker);

void* EagleWorker_begin(void *obj)
{
    EagleWorker *worker = (EagleWorker*) obj;
}

This works fine but is there a way to recover obj from the current thread without having to pass it all the way through every function? 这可以正常工作,但是是否有一种方法可以从当前线程恢复obj ,而不必始终将其传递给每个函数?

Yes. 是。 You can use thread specific data (thread local storage) to make thread wide "globals". 您可以使用线程特定的数据(线程本地存储)来使线程范围的“全局变量”成为全局变量。 The thread code can access these like normal globals. 线程代码可以像访问普通全局变量一样访问它们。 But each thread has it's own global space. 但是每个线程都有其自己的全局空间。

Try this. 尝试这个。

pthread_create(&worker->thread, NULL, EagleWorker_begin, worker);

__thread EagleWorker *worker;

void* EagleWorker_begin(void *obj)
{
    worker = (EagleWorker*) obj;

    foo();
}

void foo()
{
    worker->whatever = whatever;
}

You still need to make sure that you allocate a EagleWorker for each thread and pass it into pthread_create(). 您仍然需要确保为每个线程分配一个EagleWorker,并将其传递给pthread_create()。

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

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