说明
- unity c#使用多线程需要注意的点在注释中
- 本文做的事
代码和注释
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
/*
c# 多线程
可以执行非mono代码
可以使用基本类型和struct
不能执行 mono代码
#多线程使用模板
新建线程,设置启动参数,启动方法,开始执行,等待结果
#多线程操作
锁定变量
休眠
结束
#线程池
知识点
1、当在主线程中创建了一个线程,那么该线程的IsBackground默认是设置为FALSE的。
2、当主线程退出的时候,IsBackground=FALSE的线程还会继续执行下去,直到线程执行结束。
3、只有IsBackground=TRUE的线程才会随着主线程的退出而退出
*/
namespace DC
{
public class SimpleMultiThread : MonoBehaviour
{
Thread thread;
int sharedValue;
object sharedValueLock = new object();
void Start()
{
Debug.Log(Thread.CurrentThread.Name);
Debug.Log(Thread.CurrentThread.ManagedThreadId.ToString());
Debug.Log(Thread.CurrentThread.ToString());
SimpleUse();
StartCoroutine(TestAbort());
Debug.Log(sharedValue);
}
void WorkFunction()
{
Debug.Log("WorkFunction run 1");
Debug.Log(Thread.CurrentThread.Name);
Debug.Log(Thread.CurrentThread.ManagedThreadId.ToString());
Debug.Log(Thread.CurrentThread.ToString());
Thread.Sleep(1);
Debug.Log("WorkFunction run 2");
lock(sharedValueLock)
{
sharedValue = 10;
}
while (true)
{
//这样无法abort
//pc上,因为无法abort,前台线程都结束后这个线程即使 IsBackground = true也没有停止
// for(var i = 0; i < 10000000; i++){
// var value = Mathf.Sin(Mathf.Pow(2,16));
// }
//这样可以abort
/*
小结
正在运行的线程不能停止,除非杀死进程
如果一个线程正在进行大规模密集运算,在循环中判断是否需要停止,让线程主动结束
*/
Thread.Sleep(1000);
Debug.Log("round");
}
}
void WorkFunction(object val)
{
Debug.Log("WorkFunction run " + val.ToString());
lock(sharedValueLock)
{
sharedValue = (int)(val);
// sharedValue = int.Parse(val.ToString());
}
}
public void SimpleUse()
{
thread = new Thread(new ThreadStart(WorkFunction));
thread.Name = "worker";
thread.IsBackground = true;
thread.Start();
// thread = new Thread(new ParameterizedThreadStart(WorkFunction));
// thread.Name = "worker-param";
// thread.IsBackground = true;
// thread.Start(3);
}
public IEnumerator TestAbort()
{
yield return new WaitForSeconds(6);
thread.Abort();
Debug.Log("Abort");
}
}
}