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而不必通过每个函数一直传递它?
1 个解决方案
#1
4
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()。
#1
4
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()。