Synchronization (computer science): Difference between revisions

Content deleted Content added
Line 76:
 
==Support in programming languages==
In [[Java (programming language)|Java]], one way to prevent thread interference and memory consistency errors, is by wrappingprefixing a method signature with the ''synchronized'' keyword, in which case the lock of the declaring object is used to enforce synchronization. A second way is to wrap a block of code in a ''synchronized(someObject){...}'' section, which offers finer-grain control. This forces any thread to acquire the lock of the object represented by ''someObject'' before it can execute the contained block. The lock is automatically released when the thread which acquired the lock, and is then executing the block, leaves thethis block or enters thea waiting state within the block. Any variable updates, made by a thread in a synchronized block, become visible to other threads when they similarly acquire the lock and execute the block. Additionally, whenFor aeither methodimplementation, signatureany isobject prefixedmay withbe theused ''synchronized''to keyword,provide thea lock ofbecause theall declaringJava objectobjects ishave used.an For''intrinsic eitherlock'' ofor these''monitor implementations,lock'' anyassociated objectwith maythem bewhen used to provide the lockinstantiated.<ref>{{cite web|title=Intrinsic Locks and Synchronization|url=https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html|website=The Java Tutorials|publisher=Oracle|access-date=10 November 2023}}</ref>
 
Java ''synchronized'' blocks, in addition to enabling mutual exclusion and memory consistency, enable signaling—i.e., sending events from threads which have acquired the lock and are executing the code block to those which are waiting for the lock within the block. Java ''synchronized'' sections, therefore, combine the functionality of both [[Lock (computer science)|mutexes]] and [[Event (synchronization primitive)|events]] to ensure synchronization. Such a construct is known as a [[Monitor (synchronization)|synchronization monitor]].
 
The [[.NET Framework]] also uses synchronization primitives.<ref>{{cite web|title=Overview of synchronization primitives|url=https://learn.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives|website=Microsoft Learn|publisher=Microsoft|access-date=10 November 2023}}</ref> "Synchronization is designed to be cooperative, demanding that every thread follow the synchronization mechanism before accessing protected resources for consistent results. Locking, signaling, lightweight synchronization types, spinwait and interlocked operations are mechanisms related to synchronization in .NET." <ref>{{cite web|title=Synchronization|last=Rouse|first=Margaret|url=https://www.techopedia.com/definition/13390/synchronization-dot-net|website=Techopedia|publisher=Techopedia|access-date=10 November 2023}}</ref>
 
==Implementation==