, . , - -.
main.c
#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <assert.h>
#include <fcntl.h>
#include <semaphore.h>
void *lua_thread(void *arg)
{
int status, result, i;
double sum;
lua_State *L=(lua_State *)arg;
int a=0;
status = luaL_dofile(L, "lua_script.lua");
if (status) {
fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
exit(1);
}
printf("Lua thread exiting\n");
return 0;
}
int main(void)
{
lua_State *L;
L = luaL_newstate();
luaL_openlibs(L);
sem_t *lex=sem_open("luaexitsem", O_CREAT, 0600, 0);
int retval;
for(retval=0;retval==0;) {
retval=sem_trywait(lex);
printf("Dec sem val: %d\n", retval);
}
pthread_t p1;
pthread_create(&p1,NULL,lua_thread,L);
sleep(5);
sem_post(lex);
pthread_join(p1,NULL);
printf("Main exiting\n");
lua_close(L);
sem_close(lex);
return 0;
}
gcc -o main main.c -I/usr/include/lua5.1 -llua5.1 -lm -ldl -pthread
lua_script.lua
require "lualinuxthread"
a=1
while(not linuxthread.signaltoexit())
do
print("value of a:", a)
a=a+1
end
lualinuxthread.c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include <semaphore.h>
#include <errno.h>
#include <fcntl.h>
static int signaltoexit(lua_State *L) {
sem_t *lex=sem_open("luaexitsem", O_CREAT, 0600, 0);
int exitvalue=0, retval;
if (lex!=SEM_FAILED)
retval=sem_trywait(lex);
if (retval==-1) exitvalue=0; else exitvalue=1;
printf("signaltoexit - exitvalue: %d, retval: %d, %x\n", exitvalue, retval, lex);
lua_pushboolean(L, exitvalue);
sem_close(lex);
return 1;
}
static const luaL_Reg libfuncs[] = {
{"signaltoexit", signaltoexit},
{NULL, NULL}
};
LUALIB_API int luaopen_lualinuxthread (lua_State *L) {
luaL_register(L, "linuxthread", libfuncs);
return 1;
}
:
gcc -O -O2 -fpic -shared lualinuxthread.c -o lualinuxthread.so -lpthread -llua5.1