user215675
user215675

Reputation: 5181

C# - Multithreading - Sharing Data

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

Upvotes: 0

Views: 7312

Answers (7)

Umair Ahmed
Umair Ahmed

Reputation: 11694

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.

Upvotes: 0

monksy
monksy

Reputation: 14234

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]

Upvotes: 2

Pete Kirkham
Pete Kirkham

Reputation: 49311

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.

Upvotes: 0

AldenHurley
AldenHurley

Reputation: 128

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))

Upvotes: 2

Thanatos
Thanatos

Reputation: 44246

Yes. Some more information may be needed.

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

lock(o)
{
    // work with i.
}

Upvotes: -1

CesarGon
CesarGon

Reputation: 15325

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. :-)

Upvotes: 2

Leroy Jenkins
Leroy Jenkins

Reputation: 2770

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

Upvotes: 4

Related Questions