When using pthread, I can pass data at thread creation time.
What is the proper way of passing new data to an already running thread?
I’m considering making a global variable and make my thread read from that.
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That will certainly work. Basically, threads are just lightweight processes that share the same memory space. Global variables, being in that memory space, are available to every thread.
The trick is not with the readers so much as the writers. If you have a simple chunk of global memory, like an
int, then assigning to thatintwill probably be safe. Bt consider something a little more complicated, like astruct. Just to be definite, let’s say we haveNow
s1,s2are variables of typestruct S. We can initialize themand we can assign them
But when we assign them the processor isn’t guaranteed to complete the assignment to the whole struct in one step — we say it’s not atomic. So let’s now imagine two threads:
We can see that we’d expect
s2to have the values{42, 3.14}, {43, 6.28}, {44, 9.42}….But what we see printed might be anything like
or
and so on. The problem is that thread 1 may get control and “look at” s2 at any time during that assignment.
The moral is that while global memory is a perfectly workable way to do it, you need to take into account the possibility that your threads will cross over one another. There are several solutions to this, with the basic one being to use semaphores. A semaphore has two operations, confusingly named from Dutch as P and V.
P simply waits until a variable is 0 and the goes on, adding 1 to the variable; V subtracts 1 from the variable. The only thing special is that they do this atomically — they can’t be interrupted.
Now, do you code as
and you’re guaranteed that you’ll never have thread 2 half-completing an assignment while thread 1 is trying to print.
(Pthreads has semaphores, by the way.)