Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Lock (computer science)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Types== Generally, locks are ''advisory locks'', where each thread cooperates by acquiring the lock before accessing the corresponding data. Some systems also implement ''mandatory locks'', where attempting unauthorized access to a locked resource will force an [[exception handling|exception]] in the entity attempting to make the access. The simplest type of lock is a binary [[semaphore (programming)|semaphore]]. It provides exclusive access to the locked data. Other schemes also provide shared access for reading data. Other widely implemented access modes are exclusive, intend-to-exclude and intend-to-upgrade. Another way to classify locks is by what happens when the [[lock strategy]] prevents the progress of a thread. Most locking designs [[Blocking (computing)|block]] the [[Execution (computers)|execution]] of the [[Thread (computer science)|thread]] requesting the lock until it is allowed to access the locked resource. With a [[spinlock]], the thread simply waits ("spins") until the lock becomes available. This is efficient if threads are blocked for a short time, because it avoids the overhead of operating system process rescheduling. It is inefficient if the lock is held for a long time, or if the progress of the thread that is holding the lock depends on preemption of the locked thread. Locks typically require hardware support for efficient implementation. This support usually takes the form of one or more [[Atomic (computer science)|atomic]] instructions such as "[[test-and-set]]", "[[fetch-and-add]]" or "[[compare-and-swap]]". These instructions allow a single process to test if the lock is free, and if free, acquire the lock in a single atomic operation. [[Uniprocessor]] architectures have the option of using [[uninterruptible sequence]]s of instructions—using special instructions or instruction prefixes to disable [[interrupt]]s temporarily—but this technique does not work for [[multiprocessor]] shared-memory machines. Proper support for locks in a multiprocessor environment can require quite complex hardware or software support, with substantial [[Synchronization (computer science)|synchronization]] issues. The reason an [[atomic operation]] is required is because of concurrency, where more than one task executes the same logic. For example, consider the following [[C (programming language)|C]] code: <syntaxhighlight lang="c"> if (lock == 0) { // lock free, set it lock = myPID; } </syntaxhighlight> The above example does not guarantee that the task has the lock, since more than one task can be testing the lock at the same time. Since both tasks will detect that the lock is free, both tasks will attempt to set the lock, not knowing that the other task is also setting the lock. [[Dekker's algorithm|Dekker's]] or [[Peterson's algorithm]] are possible substitutes if atomic locking operations are not available. Careless use of locks can result in [[deadlock (computer science)|deadlock]] or [[livelock]]. A number of strategies can be used to avoid or recover from deadlocks or livelocks, both at design-time and at [[Run time (program lifecycle phase)|run-time]]. (The most common strategy is to standardize the lock acquisition sequences so that combinations of inter-dependent locks are always acquired in a specifically defined "cascade" order.) Some languages do support locks syntactically. An example in [[C Sharp (programming language)|C#]] follows: <syntaxhighlight lang="csharp"> public class Account // This is a monitor of an account { // Use `object` in versions earlier than C# 13 private readonly Lock _balanceLock = new(); private decimal _balance = 0; public void Deposit(decimal amount) { // Only one thread at a time may execute this statement. lock (_balanceLock) { _balance += amount; } } public void Withdraw(decimal amount) { // Only one thread at a time may execute this statement. lock (_balanceLock) { _balance -= amount; } } } </syntaxhighlight> C# introduced {{Mono|System.Threading.Lock}} in C# 13 on [[.NET]] 9. The code <code>lock(this)</code> can lead to problems if the instance can be accessed publicly.<ref>{{cite web|title=lock Statement (C# Reference)| date=4 February 2013 |url=http://msdn.microsoft.com/en-us/library/c5kehkcz(v=vs.100).aspx}}</ref> Similar to [[Java (programming language)|Java]], C# can also synchronize entire methods, by using the MethodImplOptions{{Not a typo|.}}Synchronized attribute.<ref> {{cite web | access-date = 2011-11-22 | page = ?? | publisher = MSDN | title = ThreadPoolPriority, and MethodImplAttribute | url = http://msdn.microsoft.com/en-us/magazine/cc163896.aspx}} </ref><ref> {{cite web |access-date=2011-11-22 |title=C# From a Java Developer's Perspective |url=http://www.25hoursaday.com/CsharpVsJava.html#attributes |url-status=dead |archive-url=https://archive.today/20130102015335/http://www.25hoursaday.com/CsharpVsJava.html |archive-date=2013-01-02 }} </ref> <syntaxhighlight lang="csharp"> [MethodImpl(MethodImplOptions.Synchronized)] public void SomeMethod() { // do stuff } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)