1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <pthread.h>
#include "thread_glue.h"
#include <VM.h>
#include <VMState.h>
void* threadFn(void* vfn)
{
ThreadStartup* ts = (ThreadStartup*)vfn;
// Make new vm data, push the argument, call the function.
VMState* vm = initstack();
// cout << "Making new vm " << vm << endl;
PUSH(new Value(NULL,KVT_NULL)); // return value
if (ts->arg!=NULL) {
PUSH(ts->arg);
}
CALLFUN(ts->fn);
return vm->doPop();
}
void* createThread(Value* fn,Value* arg)
{
ThreadStartup* ts = new ThreadStartup();
ts->fn = fn;
ts->arg = arg;
pthread_t t;
pthread_create(&t,NULL,threadFn,(void*)ts);
ThreadData* td = new ThreadData();
td->t_id = t;
return (void*)td;
}
void* createThreadNullary(Value* fn)
{
createThread(fn, NULL);
}
Value* waitForThread(void* tid)
{
ThreadData* td = (ThreadData*)tid;
void* status;
pthread_join(td->t_id,&status);
return (Value*)status;
}
void killThread(void* tid)
{
ThreadData* td = (ThreadData*)tid;
pthread_cancel(td->t_id);
}
void endThread()
{
pthread_exit(0);
}
void* createMutex()
{
pthread_mutex_t m;
pthread_mutex_init(&m,NULL);
ThreadMutex* tm = new ThreadMutex();
tm->m_id = m;
return (void*)tm;
}
void lock(void* mutex)
{
ThreadMutex* tm = (ThreadMutex*)mutex;
pthread_mutex_lock(&(tm->m_id));
}
void unlock(void* mutex)
{
ThreadMutex* tm = (ThreadMutex*)mutex;
pthread_mutex_unlock(&(tm->m_id));
}
|