Reputation: 580
I need to implement a library to work with threads in C. The user should pass the function of the thread and the argument for it, then I need to handle and create thread for it. This is the function to add new thread:
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....
}
As you can see, the user should pass function with a void type, with int param and arguments.
So I tried to add this function:
void f2(int n) {
while (1) {
printf("Thread #%d In progress:\n", n);
}
like this:
add_thread(f2, 1);
add_thread(f2, 2);
add_thread(f2, 3);
add_thread(f2, 199);
The problem is, that the argument that the function f2 gets is always -1. So I just see from all the threads:
"Thread -1 In progress"
I guess the problem is the way I am passing the arguments to makecontext()... Do you see any problem with my code?
Upvotes: 0
Views: 596
Reputation: 1
Per the man page for 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.
I see no such call to getcontext()
in your code. Is your example incomplete?
Upvotes: 0
Reputation: 75062
I googled and found a page that says that the third argument of makecontext()
should be the number of arguments. (this is the page for reference. This page is written in Japanese)
Not tested, try this:
makecontext(&uc[threadsAdded], (void (*)(void)) func, 1, arg);
Upvotes: 1