unity-多线程

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
public class duoxian : MonoBehaviour {

	// Use this for initialization
    bool m_sbstart=false;
	void Start () {
     m_sbstart=true;//开启线程
        Thread tha = new Thread(RunTread);
        tha.Start();    
	}
    
    void RunTread()
    {
        while(m_sbstart)
        {
            print("yes");
         }       
    }

    void onApplicationQuit()
    {
        m_sbstart=false;//关闭线程,避免资源泄漏或崩溃
    }
}

多线程需要注意的是什么?

  1,加锁,为什么要加锁,意思就是当有多个线程对物体进行同时的读写时,如果不进行加锁,就会出现数据混乱。                2,死锁,既然加了锁,就要避免死锁,死锁有四个必要条件,只要出现死锁,必定是因为这四种的其中一种引起的。

(1) 互斥条件:一个资源每次只能被一个进程使用。

(2) 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。

(3) 不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。

(4) 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。

 

如何加锁?

  // Use this for initialization
    int thecount = 300;
    bool m_sbstart;
    public static object c = new object();
    void Start()
    {
        m_sbstart = true;
        Thread the1 = new Thread(therun1);
        Thread the2 = new Thread(therun2);
        the1.Start();
        the2.Start();
    }

    void therun1()
    {


        for (int i = 1; i < 10; i++)
        {
            lock (c)
            {
                thecount += 1;
                Debug.Log(thecount);
            }
        }

    }

    void therun2()
    {

        for (int i = 1; i < 10; i++)
        {
            lock (c)
            {
                thecount += 100;
                Debug.Log(thecount);
            }
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值