Reputation: 1065
I'm studying C but my book offers really few resources. I'd like to know if it's possible and it's useful to use the thread to elaborate something and then pass the result to the main. In case, I'd like to know how to pass informations from a thread to the main (Something like method return in java). The only solution is to use a global variable? Here's a little example to explain what I'd like to do. Is this possible/useful?
main:
int i = 1;
pthread_create(tid,NULL,functionTH,NULL);
int z = //getResultFromThread
thread "function":
void * functionTH(){
int z = 2;
//return value 2 to the main and assign it to k in the main.
}
Upvotes: 2
Views: 122
Reputation: 6112
Memory is shared between threads, thus it's easy to just pass pointers around using queues (use one queue per thread). Also, Remember to use mutex locks and other concurrency control techniques.
Here's another S.O post which shows how to implement message passing between threads using queues.
This article titled, "Queues, Mutexes, Semaphores..," does a great job in explaining all the caveats you have to consider with race-conditions and critical sections when you're building a multi-threaded program in C.
If you're interested in learning about performance, Bartosz Milewski's article titled, "Beyond Locks and Messages: The Future of Concurrent Programming," does a great job of juxtaposing shared memory and message passing and gives great insight into the advantages of transactional memory and the disadvantages of classical locks.
Please let me know if you have any questions!
Upvotes: 1
Reputation: 17846
Look at the prototype of pthread_create.
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void*), void *restrict arg);
Your thread (start_routine
) is a function that returns a void *
. So your code is wrong since your thread function returns nothing. As you can guess, you return a value to your main thread by returning a pointer.
You can wait for the thread to complete to read this value by calling pthread_join. The value you return from the thread is passed via the value_ptr
arg.
The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated. On return from a successful pthread_join() call with a non-NULL value_ptr argument, the value passed to pthread_exit() by the terminating thread shall be made available in the location referenced by value_ptr.
Of course, you don't have to use this mechanism. Global variables can work just fine, but you do have to synchronize access to the variable or you'll end up with a race condition.
Upvotes: 3