Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading design pattern

I have an instance of a class that can be accessed by multiple threads.

Inside this class is a [ThreadStatic] variable which stores various objects.

I now need a second instance of my class, and I want it to have a separate object store inside it.

Currently, two instances in the same thread will share the same object store. I do not want this.

The only solution I can think of is:

Have a static IDictionary<int, TObjectStore> where the int is the thread id, and access this via some method or getter:

static TObjectStore ObjectStore {
    get {
        // create the instance here if its the first-access from this thread, with locking etc. for safety
        return objectStore[Thread.CurrentThread.Id];
    }
}

The problem with this though is how do I dispose of the TObjectStore for a particular thread when it ends? I think im right in assuming that with my current implementation, the GC will simply pick it up?

Thanks

like image 245
Andrew Bullock Avatar asked Jan 18 '23 19:01

Andrew Bullock


2 Answers

A static field isn't really in any instance, so I assume you now need an instance field. In that case, you want a ThreadLocal<T>:

ThreadLocal<SomeType> store = new ThreadLocal<SomeType>( () => {
    // initializer, used when a new thread accesses the value
    return ...
});

This store will be available for collection along with the instance, as will any contents (as long as they aren't referenced anywhere else, obviously).

like image 60
Marc Gravell Avatar answered Jan 20 '23 09:01

Marc Gravell


Just to provide a bit more information to Marc's answer http://blogs.clariusconsulting.net/kzu/a-better-way-to-implement-the-singleton-anti-pattern-for-easier-testing-using-ambientsingleton/

That article discusses various approaches to your problem, with code examples.

like image 35
Victor Kornov Avatar answered Jan 20 '23 09:01

Victor Kornov