Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.hpp"
- #include <iostream>
- #include <windows.h>
- #include <pthread.h>
- #include <list>
- using namespace std;
- pthread_mutex_t mutex;
- LuaPlus::LuaState* pState = LuaPlus::LuaState::Create( true );
- //-- start Task.h --
- struct Task{
- static list<Task*> runningTasks;
- static list<Task*> doneTasks;
- static pthread_mutex_t mutex;
- list<Task*>::iterator iterator;
- virtual ~Task(){}
- bool start(){
- pthread_mutex_lock(&mutex);
- bool hasSpace = runningTasks.size() < 100;
- if(hasSpace){
- runningTasks.push_front(this);
- iterator = runningTasks.begin();
- pthread_t unusedID;
- pthread_create(&unusedID, NULL, Task::threadBody, this);
- }
- pthread_mutex_unlock(&mutex);
- return hasSpace;
- }
- virtual void run() = 0;
- virtual void processResults() = 0;
- protected:
- void finish(){
- pthread_mutex_lock(&mutex);
- runningTasks.erase(iterator);
- doneTasks.push_front(this);
- pthread_mutex_unlock(&mutex);
- }
- static void* threadBody(void* instance){
- Task* task = static_cast<Task*>(instance);
- task->run();
- task->finish();
- return NULL;
- }
- };
- //-- end Task.h --
- //-- start Task.cpp --
- //Instantiate Task's static attributes
- pthread_mutex_t Task::mutex;
- list<Task*> Task::runningTasks;
- list<Task*> Task::doneTasks;
- //-- end Task.cpp --
- struct SumTask: public Task{
- int a, b, c;
- void run(){
- Sleep(3000);
- c = a+b;
- }
- void processResults(){
- LuaPlus::LuaFunction<int> CPP_OnMyEvent = pState->GetGlobal("LUA_OnMyEvent");
- CPP_OnMyEvent(a,b,c);
- }
- };
- //functions called by Lua
- bool runSumTask(int a, int b){
- SumTask *task = new SumTask();
- task->a = a; task->b = b;
- bool ok = task->start();
- if(!ok)
- delete task;
- return ok;
- }
- int gatherResults(){
- pthread_mutex_lock(&Task::mutex);
- int totalResults = Task::doneTasks.size();
- while(Task::doneTasks.size() > 0){
- Task* t = Task::doneTasks.front();
- Task::doneTasks.pop_front();
- t->processResults();
- delete t;
- }
- pthread_mutex_unlock(&Task::mutex);
- return totalResults;
- }
- int main() {
- pthread_mutex_init(&mutex, NULL); //initialize the mutex
- LuaPlus::LuaObject globals = pState->GetGlobals();
- globals.RegisterDirect("runSumTask", runSumTask);
- globals.RegisterDirect("gatherResults", gatherResults);
- char pPath[ MAX_PATH ];
- GetCurrentDirectory(MAX_PATH,pPath);
- strcat_s(pPath,MAX_PATH,"\\main.lua");
- if( pState->DoFile(pPath) ) { //run our main.lua script which contains the callback function that will run a print
- if( pState->GetTop() == 1 )
- std::cout << "An error occured: " << pState->CheckString(1) << std::endl;
- }
- //clean up
- LuaPlus::LuaState::Destroy( pState );
- pState = nullptr;
- pthread_mutex_destroy(&mutex);
- getchar(); //keep console from closing
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement