2
votes

I've written a "solution" to the producer-consumer/bounded-buffer problem using pthreads, and I use a 72 bit struct to store the data and synchronization types which are shared by all of the threads. This struct is allocated on the heap, but allocating it on the stack and passing its address in pthread_create also works. Is there any reason to prefer stack allocation over heap allocation (or vice versa) of pthread arguments in cases where pthread_detach is not used?

Edit:
The struct is declared within main(), and all threads are guaranteed to finish before main() is finished. Going out of scope is not an issue.

1
I doubt it, just be wary of data scope when passing the argument from the stack. If your data from the stack goes out of scope (when the function exits for instance), and your threads are still working on it .. UByano
given your edit, sounds like your question has more to do with when to use automatic vs dynamic storage allocation. Given the small size of your data structure, I'd use automatic. Here's one of a few questions on SO dealing with that topic: stackoverflow.com/questions/1963780/…yano
C11 draft standard n1570: 6.2.4 Storage durations of objects 5 An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration, as do some compound literals. The result of attempting to indirectly access an object with automatic storage duration from a thread other than the one with which the object is associated is implementation-defined.EOF
@EOF This is exactly the sort of answer I was looking for, thank you.Pierce Griffiths

1 Answers

1
votes

This depends on the lifetime of the stack allocated variables in relation to the running threads.

If the threads are guaranteed to exit before the stack variables go out of scope (i.e. you call pthread_join on all waiting threads) then using local variables is fine. If stack variables go out of scope while the threads are still running, then you would have to dynamically allocate them.