多线程的封装 LuaThreadPool.cs
这里是Lua的多线程执行帮助类LuaThreadPool.cs
public class LuaThreadPool
{
public FrmMain _window { get; set; } = null;
public SimulatorInfo _simulator { get; set; } = null;
public Dictionary<int , TaskList> _threads { get; set; } = new Dictionary<int, TaskList>();
}
public class TaskList
{
public CancellationTokenSource _cancel = null;
public CancellationToken _token;
public ManualResetEvent _event;
public Thread _thread;
public string _thread_status = "ready";
public async Task Start(LuaThreadPool _pool, int _vm_index = 10000)
{
_event = new ManualResetEvent(true);
_cancel = new CancellationTokenSource();
_token = _cancel.Token;
_thread = new Thread(new ThreadStart(async () =>
{
xq.Ilwsoft _lw = new xq.lwsoft();
Lua _lua = new Lua();
_lua.LuaExtendstion(_pool._window, _pool._simulator, _pool, _vm_index);
_lua["_thread_status"] = "running";
_lua["lw"] = _lw;
while (!_token.IsCancellationRequested)
{
_event.WaitOne();
Thread.Sleep(500);
_lua.DoString("xpcall(main, __G__TRACKBACK__);");
}
}));
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();
_thread_status = "running";
}
public void Stop() { _cancel.Cancel(); _thread_status = "stopped"; }
public void Pause() { _event.Reset(); _thread_status = "paused"; }
public void Continue() { _event.Set(); _thread_status = "running"; }
}
并行执行的实现
foreach (SimulatorInfo _sim in _view)
{
if (_sim.choosed == 1)
{
var _current_script = _scripts.Where(p => p != null && p._simulator.index == _sim.index).FirstOrDefault();
if (_current_script == null)
{
LuaThreadPool _pools = new LuaThreadPool() { _window = this, _simulator = _sim };
TaskList _thread = new TaskList();
await _thread.Start(_pools, _sim.index * 10000);
_pools._threads.Add(_sim.index * 10000, _thread);
_scripts.Add(_pools);
}
}
}
我在LuaThreadPool中的TaskList
1.里面有当前的线程对应的执行状态【_thread_status】
2.里面在Start中,我实例化了lw插件及lua vm虚拟机,因为只能在单例的线程中进行创建,不然会出现内存写保护。当我们需要停止的时候调用暂停直接销毁线程就好了
3.我的Lua扩展请自行根据情况进行扩展,因为多线程的Lua每个虚拟机的情况不同,所以很容易出现异常,所以需要对每个虚拟机进行相同的初始化,确保原始值的统一性。