Skip to content

Instantly share code, notes, and snippets.

@mrwonko
Created August 26, 2012 11:46
Show Gist options
  • Save mrwonko/3477951 to your computer and use it in GitHub Desktop.
Save mrwonko/3477951 to your computer and use it in GitHub Desktop.
Quick test of how multithreaded lua works
for i = 1, 20 do
print("Hello main thread world! " .. counter)
counter = counter + 1;
end
#include <lua.hpp>
#include <SFML/System.hpp>
#include <iostream>
#include <cstdlib> // system
#include <utility> // pair
// Execute a file. Print errors.
void dofile( std::pair<lua_State*, const char*> arguments )
{
lua_State* const L = arguments.first;
const char* const filename = arguments.second;
if( luaL_dofile( L, filename ) ) // returns 0 on success
{
// If there was an error, it'll be on top of the stack.
// Display and remove it.
std::cout << lua_tostring( L, -1 ) << std::endl;
lua_pop( L, 1 );
}
}
int main(int argc, char** argv)
{
// create two lua threads/states
lua_State* mainState = lua_open();
lua_State* sideState = lua_newthread( mainState ); // is now also on top of the main thread stack. shares globals.
// open base libraries (e.g. print())
luaL_openlibs( mainState );
// initialize global counter
lua_pushnumber( mainState, 0 );
lua_setglobal( mainState, "counter" );
// create two threads
sf::Thread mainThread( dofile, std::make_pair( mainState, "../main.lua" ) );
sf::Thread sideThread( dofile, std::make_pair( sideState, "../side.lua" ) );
// launch them
std::cout << "Launch!" << std::endl;
mainThread.launch();
sideThread.launch();
// wait for them to finish
mainThread.wait();
sideThread.wait();
// cleanup
lua_close( mainState );
// quick'n'dirty "press any key"
system("pause");
return 0;
}
for i = 1, 20 do
print("Hello side thread world! " .. counter)
counter = counter + 1;
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment