Ayush
Ayush

Reputation: 42450

Do I require a Thread Lock object?

Hey, I am in the process of refactoring a program that requires some amount of threading. However, I do not have much prior experience with threading, so here's a (i'm guessing) simple question I need help with.

The program watches certain files (each watcher runs on a different thread), and when a change is detected, it calls a method call Notify(). Notify() method simply sends an email.

In case two or more threads detect a change at the same time, and call Notify() at the same time, will that be a problem?

I'm guessing that since Notify() isn't accessing any file that can't be opened multiple times or any such thing, there shouldn't be a problem Notify() is called by multiple threads at the same time. But I could be wrong.

And if I am wrong, is the best method to create an object and use Lock(object) before the call to Notify()?

Upvotes: 2

Views: 166

Answers (3)

CodingGorilla
CodingGorilla

Reputation: 19842

The only reason you would need to do any locking is if there are variables inside Notify() that might be changed by multiple instances of Notify() running at the same time.

So let's say you have a List<> of files that have been detected (say, to prevent re-notification), and your Notify() method adds the file it detects to that List<>. Multiple instances of Notify() might attempt to access that list at the same time, in which case you would consider locking (or otherwise synchronizing) that List<>.

From what you've described though, I don't think you need to worry about it.

Upvotes: 2

Kadir S&#252;merkent
Kadir S&#252;merkent

Reputation: 474

If notify method uses a shared resource (like a static variable which is being used by Notify() method) you may have some threading problems and locking might be necessary, if not, there will be no problems.

Upvotes: 2

Aliostad
Aliostad

Reputation: 81660

Locking is required if multiple threads need to access shared state (static or non-static) and some of them trying to change. If all they are doing is to read, it is safe for them to access it. Also if you do not have a shared state then it is fine.

Upvotes: 2

Related Questions