【发布时间】:2013-07-16 08:40:40
【问题描述】:
如果dispatch_async创建的线程使用时间过长,例如超过5分钟,我想强制停止它。在网上搜索了一下,有人认为没有办法停止线程,有人知道吗?
在我的想象中,我想创建一个NSTimer 来在指定的时间过去时停止线程。
+ (void)stopThread:(NSTimer*)timer
{
forcibly stop the thread???
}
+ (void)runScript:(NSString *)scriptFilePath
{
[NSTimer scheduledTimerWithTimeInterval:5*60 target:self selector:@selector(stopThread:) userInfo:nil repeats:NO];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[LuaBridge runLuaFile:scriptFilePath];
});
}
我的 runLuaScript 方法:
+ (void)runLuaFile:(NSString *)filePath
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
int error2 = luaL_dofile(L, [filePath fileSystemRepresentation]);
if (error2) {
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1);
}
lua_close(L);
}
亲爱的@Martin R,我应该像那样使用 lstop,当我想停止线程时,只需调用 stopLuaRunning 方法吗?
static lua_State *L = NULL;
+ (void)runLuaFile:(NSString *)filePath
{
L = luaL_newstate();
luaL_openlibs(L);
int error2 = luaL_dofile(L, [filePath fileSystemRepresentation]);
if (error2) {
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1);
}
lua_close(L);
}
+ (void)stopLuaRunning:(lua_State *L)
{
lua_sethook(L, NULL, 0, 0);
luaL_error(L, "interrupted!");
}
【问题讨论】:
-
LuaBridge类从何而来? -
我的意思是:
LuaBridge不是标准的 Foundation 类。 你是实现它还是它是一个第三方框架? -
所以问题是
runLuaFile运行时间过长?你不能杀死一个运行块(或 NSOperation)。您必须以异步工作且可以取消的方式实现runLuaFile。 -
为什么人们不赞成投票?该问题的尝试解决方案不正确,但我认为这是一个有效的问题。
-
@StephenDarlington:你说得对,这是一个有趣的问题。
标签: ios objective-c multithreading nstimer