Reputation: 7038
Lets say I have two threads, A and B. I create Thread B
from Thread A
to access a function.
Thread A
uses the function most of time and Thread B
would rarely use it on a certain command.
If i make the function thread-safe by putting it around critical section then wouldn't it make Thread A
processing slow for each time even if Thread B
doesn't exist? Or Should i do the work of Thread B
in Thread A
itself instead of creating it?
Upvotes: 0
Views: 392
Reputation: 43472
PROFILE FIRST. Odds are good that the weight of a mutex is not going to be significant--you can lock and unlock them millions of times per second. Code correctly--using whatever locking mechanism is least prone to bugs or failure on your target system--and then, only then, if you see you need to improve performance, consider alternative strategies.
If you are expecting very low contention for the resource (i.e. the function), then a full-on mutex type may be wasteful, and depending on the particular usage pattern for the resource, a spin lock may be a viable alternative.
Upvotes: 3
Reputation: 372664
The actual performance implication of the critical section is something you'll have to measure for yourself. If the code has a lot of work relative to the number of times the critical section is entered, then chances are it won't hurt you too much. If you're doing almost no work in the critical section (for example, just incrementing a number), then you probably will see a performance hit. I'd suggest just trying out the multithreaded approach with the critical section and seeing what happens. If performance is good enough, then you don't need to worry. If it ends up being too slow, then you have some numbers to back up why you'd want to just have thread A do the processing.
Upvotes: 1