0

When a single application is executed multiple times in parallel, will statically-declared variables in that program be allocated on a single thread or duplicated among mutliple threads?

David W
  • 10,062
  • 34
  • 60
Radha Manohar
  • 409
  • 3
  • 15
  • 4
    " same program is being executed in parallel" - one exe instance with multiple threads? or multiple exe instances each with one main thread (that touches these variables)? it matters – Marc Gravell Jan 21 '20 at 10:34
  • 1
    Static variables are shared, [unless](https://stackoverflow.com/q/5227676/11683) – GSerg Jan 21 '20 at 10:34
  • @GSerg within the same exe – Jeroen van Langen Jan 21 '20 at 10:43
  • Hi - I was hoping to rephrase your question in a way that might more clearly refine what you're asking and induce helpful answers. I hope my edits reflect a correct interpretation of your question and you receive the help you need. Have a great day! – David W Jan 21 '20 at 19:56

2 Answers2

0

I have a case where a same program is being executed in parallel,

If you mean you have multiple instances of the program being executed (i.e. different processes; i.e. you are launching foo.exe multiple times), then they are entirely independent.

If you mean you have one instance of the program, which internally uses parallel threads via any mechanism: then they are entirely shared... usually.

The normal scope of a static field is: the app-domain. Almost always, this means: the process.

If your static fields are immutable (including any sub-contents of them), then: it really won't matter much; they might as well share that readonly immutable state, for efficiency. But it you are mutating the values (including mutating any sub-contents), then it gets really messy. Frankly, if a static field is non-trivially mutated in any way (other than initial setup), it probably shouldn't be a static field.

However! There is also [ThreadStatic]. If a static field is marked as [ThreadStatic], then the scope is per-thread. This is ... not a recommendation. In particular, it doesn't work with async / await at all, as you're not really in control of which thread you continue on - this means you could inadvertently switch between logical states, without realizing. Frankly, in this scenario, my recommendation would be to create an object that represents the per-thread or per-work-item state, and let each thread use that (perhaps the worker method could be an instance method on the same state object). This is very simple to grok, and makes debugging and refactoring much simpler.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

Operating system runs proceses with separated memory. So if you use separated processes, then you have different static variables. In same process static variable is alocated once for all threads.

Read about IPC: https://en.wikipedia.org/wiki/Inter-process_communication

Leszek Mazur
  • 2,443
  • 1
  • 14
  • 28