views:

53

answers:

2

I’m buried in multithreading / parallelism documents, trying to figure out how to implement a threading implementation in a programming language I’ve been designing.

I’m trying to map a mental model to the pthreads.h library, but I’m having trouble with one thing: I need my interpreter instances to continue to exist after they complete interpretation of a routine (the language’s closure/function data type), because I want to later assign other routines to them for interpretation, thus saving me the thread and interpreter setup/teardown time.

This would be fine, except that pthread_join(3) requires that I call pthread_exit(3) to ‘unblock’ the original thread. How can I block the original thread (when it needs the result of executing the routine), and then unblock it when interpretation of the child routine is complete?

+1  A: 

Use a pthread_cond_t; wait on it on one thread and signal or broadcast it in the other.

rpetrich
Just a semaphore might be sufficient in this case - init with value 0, wait on it in one thread and post it in the other. Same principle, though.
Steve Jessop
When you say ‘wait on it,’ do you mean simply a tight loop against it in the original thread? That’s … well, I was trying to avoid such a hacky/lame solution. I want to actually freeze the thread using the `pthread.h` library if I can, so that it doesn’t even get scheduled: that should save a ton of execution time, no?
elliottcable
@elliotcable: I was referring to pthread_cond_wait: http://opengroup.org/onlinepubs/007908799/xsh/pthread_cond_wait.html
rpetrich
@Steve Jessop: semaphores would likely work just as well and are simpler, but aren't technically part of pthreads though :)
rpetrich
Yeah, are they "not part of pthreads" in a troublesome way, or just in the sense that they're in a different header? Is it legal for a POSIX implementation to provide pthreads, but not provide semaphores?
Steve Jessop
@Steve Jessop: I can't imagine any POSIX implementation that would provide pthreads and not semaphores. Consider my earlier reply overly pedantic :)
rpetrich
+1  A: 

Sounds like you actually want an implementation of the Thread Pool Pattern. It makes for a fairly simple conceptual model, without repeated thread creation & tear down costs. Some OS's directly support it, on others it should be reasonably simple to implement using a queue and a semaphore.

torak
Yes, pretty much. I’m just looking for the proper `pthread.h` calls, or whatever else I need to investigate, to create this.
elliottcable