Return to Implementing Threads


From: Evan Jones <ejones@uwaterloo.ca>
Date: Mon Oct 21, 2002  17:45:20 Europe/Zurich
To: "Amit Vij" <avij@wam.umd.edu>
Subject: Re: thread library

On Sunday, Oct 20, 2002, at 23:45 Europe/Zurich, Amit Vij wrote:
> I was looking at your thread library method using makecontext, and was 
> wondering how would you would implement thread Êfunctions that had 
> parameters.Ê If you can help, please e-mail me back.

Hmm... Sure it is possible. In fact, it is quite simple using 
makecontext.

If you consult the man page (available online at 
http://www.opengroup.org/onlinepubs/007908799/xsh/makecontext.html) you 
will notice that makecontext has the following prototype:

> void makecontext(ucontext_t *ucp, (void *func)(), int argc, ...);

and the following description:

> The makecontext() function modifies the context specified by ucp, 
> which has been initialised using getcontext(). When this context is 
> resumed using swapcontext() or setcontext(), program execution 
> continues by calling func, passing it the arguments that follow argc 
> in the makecontext() call. [...] The value of argc must match the 
> number of integer arguments passed to func, otherwise the behaviour is 
> undefined.

In other words, if you want to call a function with arguments using 
makecontext, you can modify the example on my page (at 
http://www.eng.uwaterloo.ca/~ejones/software/threading.html) as follows:


          // Create the new context THIS TIME WITH ARGUMENTS
          printf( "Creating child fiber\n" );
	// NOTE THE CHANGE: I'm now passing the number of arguments, and then 
some arguments after
          makecontext( &child, &threadFunction, 2, "some argument", "one 
more argument" );


Let me know if you have any further questions,

Evan