Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use LOCK to realize thread synchronization in C #

Shulou Source: shulou.com Published: 2022-05-31 20:47:58 09月29日 Update

This article introduces the relevant knowledge of "how to use LOCK to realize thread synchronization in C#". In the operation process of actual cases, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

I. Introduction

Thread safety concept: Thread safety refers to when a thread accesses a certain data of this class, it protects it, and other threads cannot access it until the thread reads it out, and other threads can use it. There will be no data inconsistency or data contamination.

Threads may share resources with other threads, such as memory, files, databases, etc. Conflicts may arise when multiple threads read and write the same shared resource simultaneously. At this time, we need to introduce thread "synchronization" mechanism, that is, there must be a first-come-first-served between each thread, not a swarm of people to rush up to fight for a group. Thread synchronization actually means the opposite of what it means literally. Thread synchronization really means "queuing": several threads queue up to operate on shared resources one by one, rather than simultaneously.

II. Code

The following will be through a simple comparison of four cases, to explain LOCK thread synchronization to achieve the use.

Case 1:

First create two threads, two threads execute the same method, the code is as follows:

class Program { static void Main(string[] args) { Thread threadA = new Thread(ThreadMethod); //The method executed must have no return value threadA.Name = "threadA"; Thread threadB = new Thread(Thread Method); //The method executed must have no return value threadB.Name = "threadB"; threadA.Start(); threadB.Start(); Console.ReadKey(); } public static void ThreadMethod(object parameter) { for (int i = 1; i

Tags: Thread synchronization code instance result method case two key object situation data hibernation keyword at the same time meaning resource requirement security Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno MariaDB Shulou Technology Huawei Shulou Information