Advertisement
Guest User

Trying to interrupt luajit from another thread

a guest
Nov 5th, 2014
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. // build with luajit: g++ -Wall lua_limit_test.cpp -o lua_limit_test -Iinclude/luajit-2.0 -Llib -lluajit-5.1 -lpthread
  2. // build with lua:    g++ -Wall lua_limit_test.cpp -o lua_limit_test -Ilua-5.1.5/src -Llua-5.1.5/src -llua -lpthread -ldl
  3.  
  4. #include <stdio.h>
  5. extern "C" {
  6. #include "lua.h"
  7. #include "lauxlib.h"
  8. #include "lualib.h"
  9. }
  10. #include <unistd.h>
  11. #include <pthread.h>
  12.  
  13. lua_State *L;
  14. pthread_t tid;
  15.  
  16. void hook(lua_State *L, lua_Debug *ar) {
  17.     printf("hook: raising error...\n");
  18.     luaL_error(L, "interrupted by hook");
  19. }
  20.  
  21. void *thread_func(void *arg) {
  22.     printf("thread: start\n");
  23.     usleep(1000 * 1000);
  24.    
  25.     printf("thread: setting hook...\n");
  26.     int res = 0;
  27.     res = lua_sethook(L, &hook, LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT, 0);
  28.     printf("thread: hook set done for lua_State, res: %d\n", res);
  29.    
  30.     printf("thread: done\n");
  31.     return NULL;
  32. }
  33.  
  34. int main(int argc, char **argv) {
  35.     printf("main: begin\n");
  36.    
  37.     /* */
  38.     if (pthread_create(&tid, NULL, &thread_func, NULL)) {
  39.         printf("main: failed to create thread\n");
  40.         return 0;
  41.     } else {
  42.         printf("main: started thread %ld\n", tid);
  43.     }
  44.     /* */
  45.    
  46.     L = luaL_newstate();
  47.     luaL_openlibs(L);
  48.    
  49.     // thread_func(NULL);
  50.    
  51.     printf("main: executing LUA code...\n");
  52.     int res = luaL_dostring(L, "local x = 0; for v = 0, 1e+15, 1 do x = x + 1; end;");
  53.     printf("main: LUA code done, res: %d\n", res);
  54.    
  55.     if (res) {
  56.         const char *err = lua_tostring(L, -1);
  57.         printf("main: LUA error: %s\n", err);
  58.     }
  59.    
  60.     printf("main: waiting for thread to complete...\n");
  61.     pthread_join(tid, NULL);
  62.    
  63.     printf("main: done\n");
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement