Should I run each plugin in its own thread?
In my game a user can load custom scripts. Typically there are 50-100 scripts loaded. Each script gets called each frame via its Update method.
- When a script crashes the other scripts should not be affected.
- A scripts Update method is allowed to run for a maximum of 1 millisecond each frame. So I also need to be able to Abort scripts that are frozen / not reactin开发者_JAVA百科g in time.
How should I do this? I think that starting 3000 - 6000 threads per second is not the best practice here. I also cannot start threads once that call Update in a loop and wait 16ms because the scripts need to be synchronized with game. The scripts depend on being run every frame.
Is a threadpool the right choice here? And if so, how am I gonna abort scripts that timeout?
Short: protecting agains hostile code is hard.
1. When a script crashes the other scripts should not be affected: to achieve this the only reliable way in Windows is to run each script in separate process. I.e. StackOverflow exception caused by a "script" will bring your process down. Cross-process communication is unlikely to easily match your performance requirement.
2. 1 ms each script: aborting thread is a solution. Avoid huge number of threads (going above tens threads is questionable: switching between threads can kill your performance, stack space eats all memory and in general synchronyzing state cross thread is fun). Consider not restarting "scripts" that behaved poorely - this way you don't need to worry about too many Thread.Abort calls. Note that killing thread not necessary will kill everything related to "script" as it may have spawned own threads/asynchronous operations/thread pool tasks...
精彩评论