LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Thread spawning with the same function (https://www.linuxquestions.org/questions/linux-newbie-8/thread-spawning-with-the-same-function-4175494201/)

jayadhanesh 02-07-2014 05:53 PM

Thread spawning with the same function
 
Hi,

I want to create multiple threads, but all the thread should be spawned using the same function. If I use the same function name for all the threads during pthread_create, then will each thread have its own copy of the function?

Thanks,
D

jlinkels 02-07-2014 08:36 PM

No. It is the same code. But because each function allocates its own stack frame, the data is local to each thread.

That is how it should be done. As soon as you use static variables your function is not "thread-safe" in most cases. If you access global variables in your function might not be thread safe. You have to take special precautions to keep it thread safe.

jlinkels

jayadhanesh 02-08-2014 12:46 PM

Thanks for the reply. My function have local variables and one global. So if I use some locking mechanism for the global variable, am I ok?

Thanks,
D

jlinkels 02-09-2014 07:19 AM

If your local variables are not static, yes.

"Some locking" mechanism is a somewhat sloppy term. You have to use a carefully designed, well thought locking policy. The problem is not so much in protecting the integrity of the variables, but in the avoidance of lock conditions. There are a couple of standard functions in the thread library which deal with locking, like semaphores.

I am not opposed to threads at all, but some people are and describe the problems they can cause:
http://www.eecs.berkeley.edu/Pubs/Te...ECS-2006-1.pdf
And Google will turn up many more documents.

jlinkels

jayadhanesh 02-10-2014 01:06 AM

Thanks again. One more clarification. If I pass a pointer to a same structure to all the threads that I spawn, will the changes
to the struct in one thread be reflected on the other thread, or a local copy of the pointer is created for each thread?

Thanks,
D

pan64 02-10-2014 01:11 AM

just imagine, the local variables belong to the current thread, global variables are accessible from every thread. Pointers will point to a "global" memory, therefore it will be common for all the threads. (The pointer itself can be local).


All times are GMT -5. The time now is 05:46 AM.