ljuv (halted)

Diff
Login

Differences From Artifact [c8b2b3cdfe]:

To Artifact [26046ae670]:


207
208
209
210
211
212
213


214
215
216
217
218
219
220
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222







+
+







// Thread

typedef struct ljuv_thread{
  uv_thread_t handle;
  uv_mutex_t mutex;
  lua_State *L;
  bool running;
  char *data;
  size_t data_size;
} ljuv_thread;

static const char thread_lua[] =
  "local function pack(...) return {n = select('#', ...), ...} end\n\
  local buffer = require('string.buffer')\n\
  local errtrace\n\
  local function error_handler(err) errtrace = debug.traceback(err, 2) end\n\
235
236
237
238
239
240
241









242

243
244
245
246
247
248
249
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261







+
+
+
+
+
+
+
+
+

+







void thread_run(void *arg)
{
  ljuv_thread *thread = arg;
  lua_State *L = thread->L;
  luaL_openlibs(L);
  luaL_loadbuffer(L, thread_lua, strlen(thread_lua), "=[ljuv thread]");
  lua_call(L, 0, 0);
  // handle return data
  lua_getglobal(thread->L, "ljuv_data");
  const char* data_ptr = lua_tolstring(thread->L, -1, &thread->data_size);
  if(data_ptr && thread->data_size > 0){
    thread->data = malloc(thread->data_size);
    if(thread->data) memcpy(thread->data, data_ptr, thread->data_size);
  }
  else
    thread->data = NULL;
  // end
  lua_close(thread->L);
  uv_mutex_lock(&thread->mutex);
  thread->running = false;
  uv_mutex_unlock(&thread->mutex);
}

// Create thread.
// return NULL on failure
283
284
285
286
287
288
289
290
291
292

293
294
295
296
297

298
299
300
301
302
303
304
295
296
297
298
299
300
301



302





303
304
305
306
307
308
309
310







-
-
-
+
-
-
-
-
-
+







// return true on success
//
// On success, thread data are released and data/size are filled.
// The data pointer, if not NULL, must be freed with free().
bool thread_join(ljuv_thread *thread, char **data, size_t *size)
{
  if(uv_thread_join(&thread->handle) == 0){
    lua_getglobal(thread->L, "ljuv_data");
    const char* data_ptr = lua_tolstring(thread->L, -1, size);
    *data = NULL;
    *data = thread->data;
    if(data_ptr && *size > 0){
      *data = malloc(*size);
      if(*data) memcpy(*data, data_ptr, *size);
    }
    lua_close(thread->L);
    *size = thread->data_size;
    uv_mutex_destroy(&thread->mutex);
    free(thread);
    return true;
  }
  else return false;
}