c 中的线程无法将函数正确传递给 makecontext()
Threads in c can't pass function properly to makecontext()
我需要实现一个库来使用 C 中的线程。
用户应该传递线程的函数和它的参数,然后
我需要为它处理和创建线程。
这是添加新线程的函数:
int add_thread(void (*func)(int), int arg) {
printf("Adding thread #%d with arg:[%d] \n", threadsAdded, arg);
////// create the thread.....
makecontext(&uc[threadsAdded], (void (*)(void)) func, arg);
More none important things....
}
如您所见,用户应该传递具有 void 类型的函数,以及 int 参数和参数。
所以我尝试添加这个功能:
void f2(int n) {
while (1) {
printf("Thread #%d In progress:\n", n);
}
像这样:
add_thread(f2, 1);
add_thread(f2, 2);
add_thread(f2, 3);
add_thread(f2, 199);
问题是,函数 f2 得到的参数总是 -1。
所以我只从所有线程中看到:
"Thread -1 In progress"
我想问题出在我将参数传递给 makecontext() 的方式...您是否发现我的代码有任何问题?
我用谷歌搜索了一下,发现一个页面说 makecontext()
的第三个参数应该是参数的个数。 (this is the page 供参考。本页为日文)
未测试,试试这个:
makecontext(&uc[threadsAdded], (void (*)(void)) func, 1, arg);
根据 man page makecontext
:
void makecontext(ucontext_t *ucp, void (*func)(), int argc, ...);
...
The makecontext() function modifies the context pointed to by ucp
(which was obtained from a call to getcontext(3)). Before invoking
makecontext(), the caller must allocate a new stack for this context
and assign its address to ucp->uc_stack, and define a successor
context and assign its address to ucp->uc_link.
我在您的代码中没有看到对 getcontext()
的此类调用。你的例子不完整吗?
我需要实现一个库来使用 C 中的线程。 用户应该传递线程的函数和它的参数,然后 我需要为它处理和创建线程。 这是添加新线程的函数:
int add_thread(void (*func)(int), int arg) {
printf("Adding thread #%d with arg:[%d] \n", threadsAdded, arg);
////// create the thread.....
makecontext(&uc[threadsAdded], (void (*)(void)) func, arg);
More none important things....
}
如您所见,用户应该传递具有 void 类型的函数,以及 int 参数和参数。
所以我尝试添加这个功能:
void f2(int n) {
while (1) {
printf("Thread #%d In progress:\n", n);
}
像这样:
add_thread(f2, 1);
add_thread(f2, 2);
add_thread(f2, 3);
add_thread(f2, 199);
问题是,函数 f2 得到的参数总是 -1。 所以我只从所有线程中看到:
"Thread -1 In progress"
我想问题出在我将参数传递给 makecontext() 的方式...您是否发现我的代码有任何问题?
我用谷歌搜索了一下,发现一个页面说 makecontext()
的第三个参数应该是参数的个数。 (this is the page 供参考。本页为日文)
未测试,试试这个:
makecontext(&uc[threadsAdded], (void (*)(void)) func, 1, arg);
根据 man page makecontext
:
void makecontext(ucontext_t *ucp, void (*func)(), int argc, ...); ... The makecontext() function modifies the context pointed to by ucp (which was obtained from a call to getcontext(3)). Before invoking makecontext(), the caller must allocate a new stack for this context and assign its address to ucp->uc_stack, and define a successor context and assign its address to ucp->uc_link.
我在您的代码中没有看到对 getcontext()
的此类调用。你的例子不完整吗?