The use of Unity multi-threaded Lock (multi-threaded use of dictionary storage problems)

The use of Lock:
It is equivalent to creating a lock for the dictionary.
Using a dictionary to store in multi-threading may have the problem of incomplete dictionary data. This method needs to be added.

//在多线程中使用字典等添加数据时,需要使用
private static readonly object  Locker = new object();


     lock (Locker)
     {
    
    
         dir.Add(index, buffer.Length);
     }

Example: If this method is not used, list.count is not 5000

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{
    
    
    object locker=new object();
    List<string> list=new List<string>();
    void Start()
    {
    
    
        for (int i = 0; i < 50; i++)
        {
    
    
            Thread thread = new Thread(Tes);
            thread.Start();
        }
    }
    void Tes()
    {
    
    
        for (int i = 0; i < 100; i++)
        {
    
    
            lock (locker)
            {
    
    
                list.Add(i.ToString());
            }
            
        }
    }
    
    void Update()
    {
    
    
        if (Input.GetMouseButtonDown(1))
        {
    
    
            Debug.Log(list.Count);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_45598937/article/details/127551770