Reputation: 179
Say you have two threads in Win32. Let's say the main UI thread launches a worker thread A. Let's say when Thread A was created a pointer back to a class in the main thread was sent to thread A. At some point during it's processing, Thread A calls a function in the main thread via the pointer. Thread A and the main thread will never contend for the same data and never call the same function at the same time.
Is this bad practice?
And if it is then what would be the correct design for this functionality. Thread A needs access to the function in the main thread say to access data kept in the main thread. It's expected though that Thread A will never call the function in the main thread when the main thread is accessing the data. Thus there would be no contention over the data. However, the main thread may start up again while thread a is still calling into the function in the main thread.
Does this matter or is it generally OK to call functions in other threads so long as there is no data contention and the functions being called into are reentrant?
Upvotes: 0
Views: 1255
Reputation: 612854
Threads are global in a process, shared between all threads. There's no such thing as "a function in the main thread".
What matters is how the data is shared. A function consists of two things: the code itself, and the data that it operates on.
The code is, as a general rule, static. This is why it is fine for code to be freely shared between threads. There is never any contention on it.
It's a different story for the data though. You need to be sure that there is no incorrect contention on any data shared between multiple threads. So long as you are content that this is so, then it is fine to call the same function from multiple threads.
Upvotes: 2