Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I was reading up on design patterns, to better my understandings of ones I know and reveal ones I didn't. One of the last ones I looks at was the Flyweight Pattern. It preaches about shared common function, and I understand this. Keeping with the game example (in the link), sharing functions for units in an RTS I'm sure would save on memory. But would this not sacrifice a great deal of [speed] performance?

Keeping with the RTS theme, suppose you have 300 units on the field, all sharing the same run function, would this not be an asynchronous nightmare? And if one was do perform this in-line (via maybe a step/render style engine), would this not bog the the CPU?

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

Just because code is shared over threads doesn't mean that it is not thread safe. Only when threads share mutable state does it need to be synchronized; note that code is immutable.

also the code for each function is stored once in memory (barring optimizations) even if there are hundreds of objects and can be used by multiple threads at the same time as long as the data it acts upon is different.

share|improve this answer
    
Ok, I see, that does make it make much more sense. –  AedonEtLIRA Mar 13 '12 at 21:45
    
@ratchetfreak: code is immutable in /most/ cases. There is such a thing as self modifying code. –  jmoreno Mar 14 '12 at 3:29
    
@jmoreno Do you have an example of some? I think I know what you are talking about, but I would like to be sure. –  AedonEtLIRA Mar 14 '12 at 17:22
    
@AedonEtLIRA: I think the wikipedia article adequately covers it. Code can be modified while running, before running, when finishing running. You obviously need to get the new code right, but then again you want to get all of your code right... –  jmoreno Mar 15 '12 at 3:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.