Thread-safe class instances
Posted on 2003-03-04
How do I make class methods thread-safe for each particular class instance, without threads for one instance interfering with the threads for the other instances?
// I have a few instances of MyClass
MyClass A, B, C;
// And I have a thread function, using MyClass instance
ThreadFunction(MyClass * pMyClass)
Then I am launching a lot of ThreadFunction threads, passing to each a pointer to the MyClass instance (pointer to A, B or C). Each instance (like A) may be passed to several threads; the total number of instances is not limited. I need all threads using instance A be thread-safe with respect to each other; same for all threads using instance B, etc. However, all A-threads should not block any of B-threads, etc. For example, A, B, C,… may be different files, and ThreadFunction(…) may be a file-writing function. In this case, all threads writing to the same file should be safe, but they should not interfere with the threads writing to the other files.
My app runs under Windows. If possible, I would like to avoid creating a critical section for each class instance. I also need the most time-efficient solution. I am new to thread-safe programming, so please be specific.