2015-12-05 79 views
0

我需要实现库来处理C中的线程。 用户应该传递线程的函数和它的参数,而不是 我需要处理和创建线程它。 这是添加新的线程功能:线程c正确传递函数makecontext

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.... 

}

正如你所看到的,用户应与INT PARAM和参数类型为void通功能。

于是,我就添加此功能:

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。 所以我刚刚从所有的线程看到:

“主题-1在进步”

我想这个问题是我传递的参数makecontext的方式......你看到的任何问题与我的代码?

回答

1

我搜索了一下,发现一个页面说makecontext()的第三个参数应该是参数的个数。 (this is the page参考此页日文版)

没有测试,试试这个:

makecontext(&uc[threadsAdded], (void (*)(void)) func, 1, arg); 
0

man pagemakecontext

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()。你的例子不完整吗?