![]() |
VOOZH | about |
C# makes the concurrent execution of a code possible with the help of threads. The namespace System. Threading which is pre-built in C# supports the use of threads. Typically we create threads for the concurrent execution of a program. But in certain cases we may not want our program to be run concurrently by more than 1 thread i.e. we want to prevent simultaneous access to a resource by multiple threads. The resource here may refer to a data type or variable that is created in the C# program.
To avoid the above condition, C# has an inbuilt keyword 'lock' that prevents simultaneous access to a resource by two threads. The syntax of lock keyword is shown below:
Syntax:
lock(name_of_object) statements_to_be_executed_after_lock
Note: It is important to make use of System.Threading namespace to implement threading and locking.
Let us have a look at how the lock in C# works:
The implementation of locks will be explained by an example. Let us first see a program without the use of locks.
Example 1:
Output:
HHeelllloo WWoorrlldd
The above program is a simple code where two threads execute a function which prints the characters of a string. As it can be seen from the output, the second thread begins its execution even when the first has not completed its execution.
Now let us see a program with the use of locks.
Example 2:
Output:
Hello World Hello World
In this program, we need to create an object that will be responsible for locking. The statements to be executed are then written inside the block of this object. As we can see from the output that both the threads execute the code block one by one instead of concurrent execution when the thread lock is implemented.