将指针附加到 pthread
Attaching a pointer to a pthread
在我的程序中,我有一个名为 clock_thread
的结构,它对我的线程系统至关重要。它基本上是一个线程,以恒定的速率执行操作。
有时一些功能需要与 clock_thread
同步,但为此,它们需要当前的 clock_thread
。我无法通过参数传递 clock_thread
。我知道我可以通过 pthread_self()
获取当前的 pthread
,但我需要以某种方式附加一个指向 pthread
的指针,它指向 clock_thread
结构。
我目前知道的唯一方法是使用一个全局数组来跟踪所有 clock_thread
,并在需要时比较每个 clock_thread
的 pthread
与当前
pthread
与 pthread_equal
。
例如,clock_thread
确实不断调用方法 do_stuff()
,理论上它可以做任何事情。 clock_thread
的唯一目的是调用函数,它与函数的功能无关。那么这个函数可能会调用perform_write
,需要改变另一个clock_thread的状态。所以它需要知道当前的 clock_thread
但 do_stuff()
不需要通过其逻辑一直传递当前的 clock_thread
。在实际函数中,do_stuff
代码要复杂得多,并且由于风格选择,我无法将当前 clock_thread
作为参数传递。
struct clock_thread memory_thread;
void perform_read(uint16_t addr, uint16_t value) {
//Needs to sync with other thread
//But how
clock_thread_sync(???, memory_thread);
}
void do_stuff() {
//Do some stuff
perform_write(addr, 0x1234);
}
有没有更好的方法来完成这个?我想尽可能避免使用全局变量。
我解决了这个问题,因为 do_something()
函数知道它在哪个线程中(它有一个指针指向的另一个结构)。 perform_read()
现在将当前 clock_thread
作为参数
在我的程序中,我有一个名为 clock_thread
的结构,它对我的线程系统至关重要。它基本上是一个线程,以恒定的速率执行操作。
有时一些功能需要与 clock_thread
同步,但为此,它们需要当前的 clock_thread
。我无法通过参数传递 clock_thread
。我知道我可以通过 pthread_self()
获取当前的 pthread
,但我需要以某种方式附加一个指向 pthread
的指针,它指向 clock_thread
结构。
我目前知道的唯一方法是使用一个全局数组来跟踪所有 clock_thread
,并在需要时比较每个 clock_thread
的 pthread
与当前
pthread
与 pthread_equal
。
例如,clock_thread
确实不断调用方法 do_stuff()
,理论上它可以做任何事情。 clock_thread
的唯一目的是调用函数,它与函数的功能无关。那么这个函数可能会调用perform_write
,需要改变另一个clock_thread的状态。所以它需要知道当前的 clock_thread
但 do_stuff()
不需要通过其逻辑一直传递当前的 clock_thread
。在实际函数中,do_stuff
代码要复杂得多,并且由于风格选择,我无法将当前 clock_thread
作为参数传递。
struct clock_thread memory_thread;
void perform_read(uint16_t addr, uint16_t value) {
//Needs to sync with other thread
//But how
clock_thread_sync(???, memory_thread);
}
void do_stuff() {
//Do some stuff
perform_write(addr, 0x1234);
}
有没有更好的方法来完成这个?我想尽可能避免使用全局变量。
我解决了这个问题,因为 do_something()
函数知道它在哪个线程中(它有一个指针指向的另一个结构)。 perform_read()
现在将当前 clock_thread
作为参数