Skip to content

Commit

Permalink
main: Add support for external threads attaching/detaching re context. (
Browse files Browse the repository at this point in the history
#414)

This commit allows to create an event loop context and keep a reference
to it in the caller application. After that, this and other threads
are allowed to attach to and detach from this context as needed. Threads
are synchronized by calling re_thread_enter/leave. The re context can
be destroyed by calling mem_deref.

This is useful to allow threads that are not running event loop to
invoke methods on an event loop context that is created and managed by
another thread.
  • Loading branch information
Lastique authored Jun 25, 2022
1 parent cc3dbc4 commit c0cb714
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
5 changes: 5 additions & 0 deletions include/re_main.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* Copyright (C) 2010 Creytiv.com
*/

struct re;

enum {
#ifndef FD_READ
Expand Down Expand Up @@ -44,6 +45,10 @@ int re_main(re_signal_h *signalh);
void re_cancel(void);
int re_debug(struct re_printf *pf, void *unused);

int re_alloc(struct re **rep);
int re_thread_attach(struct re *re);
void re_thread_detach(void);

int re_thread_init(void);
void re_thread_close(void);
void re_thread_enter(void);
Expand Down
38 changes: 37 additions & 1 deletion src/main/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ static void thread_destructor(void *arg)
}


static int re_alloc(struct re **rep)
int re_alloc(struct re **rep)
{
struct re *re;
int err;
Expand Down Expand Up @@ -1320,6 +1320,42 @@ void re_thread_leave(void)
}


/**
* Attach the current thread to re context
*/
int re_thread_attach(struct re *context)
{
struct re *re;

if (!context)
return EINVAL;

call_once(&flag, re_once);

re = tss_get(key);
if (re) {
if (re != context)
return EALREADY;
return 0;
}

tss_set(key, context);

return 0;
}


/**
* Detach the current thread from re context
*/
void re_thread_detach(void)
{
call_once(&flag, re_once);

tss_set(key, NULL);
}


/**
* Set an external mutex for this thread
*
Expand Down

2 comments on commit c0cb714

@juha-h
Copy link
Contributor

@juha-h juha-h commented on c0cb714 Jun 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these three new API functions alternative to re_thread_init (called by libre_init) and re_thread_enter/leave?

@sreimers
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are only needed if you need more control and want to avoid the re_global fallback for non-re threads.

Please sign in to comment.