views:

406

answers:

7

Is it possible for threads to share data (Global Variables) in same process.

+4  A: 

Have you read the following article? http://msdn.microsoft.com/en-us/magazine/cc163744.aspx

Leroy Jenkins
+1  A: 

Of course it is. You just need to synchronise them to avoid deadlocks. Use lock in C# to mark a critical section in code. Check MSDN for details. :-)

CesarGon
A: 

Yes. Some more information may be needed.

Object o = new Object();
int i; // Shared variable

lock(o)
{
    // work with i.
}
Thanatos
+1  A: 

It is possible for multiple threads within the same program to share data. However you must be aware of potential issues with data access, and writting. Typically this will bring up issues with reading while writing, or trying to access the same resource. [See more about race condictions]

monksy
+1  A: 

Yes it definitely is, either via references to static objects, overtly providing reference across threads, or by marshaling across threads (e.g. UI control invoke/dispatch calls, although that's not exactly the same).

While synchronization of shared resources across threads is definitely important simply advocating a lock(object) as a blanket approach isn't necessarily appropriate in all circumstances. If you have two threads each locked on a shared object that the other thread is waiting on you'll deadlock so some consideration must be paid to design and process flow.

Also take head not to lock entire classes unless necessary, doing so may provide unnecessary overhead and result in performance loss. For static classes that require synchronization it may be best to provide a static object to lock for methods that interact with shared state instead of locking the entire class: e.g. lock(_staticLockObjectInstance) over lock(typeof(staticClass))

AldenHurley
+1  A: 

Have a look on a very nice post by Jon Skeet. Its a good read even for those who are a bit comfortable in threading.

Umair Ahmed
A: 

The default behaviour of threads in the same process is to share global storage.

If you don't want shared storage, then the environment provides thread local storage.

If you do access shared storage, then you probably need to synchronize access to the storage, either using locks, atomic operations or memory fences. If you forget to do that in any part of the code, it may fail in unpredictable ways.

Pete Kirkham