views:

107

answers:

2

In a program, I can design lock to threads,lock to object or files. Are there difference between these locks? If yes, how many kinds of lock are there which can be used to design?

Are there some tutorials to design locks in object-oriented programming?

A: 

The answer depends on the context of your question.

Are you obtaining locks from some API? Check the API documentation.

In general, though, I would say no. A lock is a lock. The fact that you are using it to protect a file or an object does not matter to the API. How you use it is up to you. You certainly could abstract away and have FileLocks and ObjectLocks if you wish, but that is up to you.

dss539
+1  A: 

As someone dss538 said, the "answer" really depends on the context of the question.

What exactly is it that you need to protect access to?

An piece of data or single object, items in a container of some sort, a piece of code, a system resource like a shared file?

Another really meaningful question is how frequently are you going to be accessing this "thing" and what are you going to do with it?

Different locking techniques tend to have different overheads and while a critical section or mutex may be perfectly fine for something that is rarely accesseed and rarely updated, if you're rarely updating it and frequently accessing it you might want to look at a reader writer lock. Another follow up question here is "should I be using spin-locks" here, and again the answer is it depends? What else is going on in the system and are you going to trade one kind of bottleneck (a coarse grained lock) for another?

A final question I like to ask is what are the alternatives to "locking" something, i.e. if I can "safely" take a copy of my protected thing and work with that copy "safely" (ideally without modifying it), it's certainly a lot easier than worrying about every place I might modify said "thing."

I apologize for the vague answer but a more specific question would help here.

I would encourage you to read up on concurrency prinicples and understand the traditional "Dining Philosopers" "Sleeping Barber" and perhaps even "Santa Clause" problems to understand more context of how these things work.

A lot of the content on Wikipedia is good, particularly 'Concurrency Control' is a useful starting reference point if you don't have a good OS / Concurrency book on your shelf.

Rick
@Rick: What if the data structure is frequently updated?
Jinx