【问题标题】:Threads in c can't pass function properly to makecontext()c 中的线程无法将函数正确传递给 makecontext()
【发布时间】:2015-12-05 14:49:38
【问题描述】:

我需要实现一个库来处理 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。 所以我只是从所有线程中看到:

“线程 -1 进行中”

我想问题是我将参数传递给 makecontext() 的方式...你看到我的代码有什么问题吗?

【问题讨论】:

    标签: c multithreading parameter-passing


    【解决方案1】:

    我用谷歌搜索,发现一个页面说makecontext() 的第三个参数应该是参数的数量。 (this is the page供参考,本页为日文)

    未测试,试试这个:

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

    【讨论】:

      【解决方案2】:

      根据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() 的此类调用。你的例子不完整吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-27
        • 1970-01-01
        • 1970-01-01
        • 2016-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多