--- Coro/Coro/State.xs 2008/11/16 11:12:57 1.283 +++ Coro/Coro/State.xs 2008/11/22 06:03:10 1.323 @@ -18,7 +18,7 @@ # undef setjmp # undef longjmp # undef _exit -# define setjmp _setjmp // deep magic, don't ask +# define setjmp _setjmp /* deep magic */ #else # include /* most portable stdint.h */ #endif @@ -57,7 +57,7 @@ (PERL_REVISION > (a) \ || (PERL_REVISION == (a) \ && (PERL_VERSION > (b) \ - || (PERL_VERSION == (b) && PERLSUBVERSION >= (c))))) + || (PERL_VERSION == (b) && PERL_SUBVERSION >= (c))))) #if !PERL_VERSION_ATLEAST (5,6,0) # ifndef PL_ppaddr @@ -97,6 +97,15 @@ #ifndef newSV # define newSV(l) NEWSV(0,l) #endif +#ifndef CvISXSUB_on +# define CvISXSUB_on(cv) (void)cv +#endif +#ifndef CvISXSUB +# define CvISXSUB(cv) (CvXSUB (cv) ? TRUE : FALSE) +#endif +#ifndef Newx +# define Newx(ptr,nitems,type) New (0,ptr,nitems,type) +#endif /* 5.8.7 */ #ifndef SvRV_set @@ -119,9 +128,11 @@ /* The next macros try to return the current stack pointer, in an as * portable way as possible. */ #if __GNUC__ >= 4 -# define dSTACKLEVEL void *stacklevel = __builtin_frame_address (0) +# define dSTACKLEVEL int stacklevel_dummy +# define STACKLEVEL __builtin_frame_address (0) #else -# define dSTACKLEVEL volatile void *stacklevel = (volatile void *)&stacklevel +# define dSTACKLEVEL volatile void *stacklevel +# define STACKLEVEL ((void *)&stacklevel) #endif #define IN_DESTRUCT (PL_main_cv == Nullcv) @@ -142,6 +153,7 @@ #define NOINLINE attribute ((noinline)) #include "CoroAPI.h" +#define GCoroAPI (&coroapi) /* very sneaky */ #ifdef USE_ITHREADS # if CORO_PTHREAD @@ -149,18 +161,12 @@ # endif #endif -/* helper storage struct for Coro::AIO */ -struct io_state -{ - AV *res; - int errorno; - I32 laststype; /* U16 in 5.10.0 */ - int laststatval; - Stat_t statcache; -}; - static double (*nvtime)(); /* so why doesn't it take void? */ +/* we hijack an hopefully unused CV flag for our purposes */ +#define CVf_SLF 0x4000 +static OP *pp_slf (pTHX); + static U32 cctx_gen; static size_t cctx_stacksize = CORO_STACKSIZE; static struct CoroAPI coroapi; @@ -169,6 +175,9 @@ static HV *coro_state_stash, *coro_stash; static volatile SV *coro_mortal; /* will be freed/thrown after next transfer */ +static AV *av_destroy; /* destruction queue */ +static SV *sv_manager; /* the manager coro */ + static GV *irsgv; /* $/ */ static GV *stdoutgv; /* *STDOUT */ static SV *rv_diehook; @@ -178,7 +187,11 @@ /* async_pool helper stuff */ static SV *sv_pool_rss; static SV *sv_pool_size; -static AV *av_async_pool; +static SV *sv_async_pool_idle; /* description string */ +static AV *av_async_pool; /* idle pool */ +static SV *sv_Coro; /* class string */ +static CV *cv_pool_handler; +static CV *cv_coro_state_new; /* Coro::AnyEvent */ static SV *sv_activity; @@ -217,6 +230,10 @@ unsigned char flags; } coro_cctx; +coro_cctx *cctx_current; /* the currently running cctx */ + +/*****************************************************************************/ + enum { CF_RUNNING = 0x0001, /* coroutine is running */ CF_READY = 0x0002, /* coroutine is ready */ @@ -243,15 +260,16 @@ /* the C coroutine allocated to this perl coroutine, if any */ coro_cctx *cctx; - /* process data */ + /* state data */ struct CoroSLF slf_frame; /* saved slf frame */ AV *mainstack; perl_slots *slot; /* basically the saved sp */ - AV *args; /* data associated with this coroutine (initial args) */ - int refcnt; /* coroutines are refcounted, yes */ - int flags; /* CF_ flags */ - HV *hv; /* the perl hash associated with this coro, if any */ + CV *startcv; /* the CV to execute */ + AV *args; /* data associated with this coroutine (initial args) */ + int refcnt; /* coroutines are refcounted, yes */ + int flags; /* CF_ flags */ + HV *hv; /* the perl hash associated with this coro, if any */ void (*on_destroy)(pTHX_ struct coro *coro); /* statistics */ @@ -259,10 +277,13 @@ /* coro process data */ int prio; - SV *throw; /* exception to be thrown */ + SV *except; /* exception to be thrown */ + SV *rouse_cb; /* async_pool */ SV *saved_deffh; + SV *invoke_cb; + AV *invoke_av; /* linked list */ struct coro *next, *prev; @@ -271,6 +292,9 @@ typedef struct coro *Coro__State; typedef struct coro *Coro__State_or_hashref; +/* the following variables are effectively part of the perl context */ +/* and get copied between struct coro and these variables */ +/* the mainr easonw e don't support windows process emulation */ static struct CoroSLF slf_frame; /* the current slf frame */ /** Coro ********************************************************************/ @@ -286,6 +310,7 @@ static SV *coro_current; static SV *coro_readyhook; static AV *coro_ready [PRIO_MAX - PRIO_MIN + 1]; +static CV *cv_coro_run, *cv_coro_terminate; static struct coro *coro_first; #define coro_nready coroapi.nready @@ -321,8 +346,17 @@ return get_hv (name, create); } +/* may croak */ +INLINE CV * +coro_sv_2cv (pTHX_ SV *sv) +{ + HV *st; + GV *gvp; + return sv_2cv (sv, &st, &gvp, 0); +} + static AV * -coro_clone_padlist (pTHX_ CV *cv) +coro_derive_padlist (pTHX_ CV *cv) { AV *padlist = CvPADLIST (cv); AV *newpadlist, *newpad; @@ -382,7 +416,7 @@ return 0; } -#define CORO_MAGIC_type_cv PERL_MAGIC_ext +#define CORO_MAGIC_type_cv 26 #define CORO_MAGIC_type_state PERL_MAGIC_ext static MGVTBL coro_cv_vtbl = { @@ -390,15 +424,18 @@ coro_cv_free }; -#define CORO_MAGIC(sv, type) \ - expect_true (SvMAGIC (sv)) \ - ? expect_true (SvMAGIC (sv)->mg_type == type) \ - ? SvMAGIC (sv) \ - : mg_find (sv, type) \ - : 0 +#define CORO_MAGIC_NN(sv, type) \ + (expect_true (SvMAGIC (sv)->mg_type == type) \ + ? SvMAGIC (sv) \ + : mg_find (sv, type)) + +#define CORO_MAGIC(sv, type) \ + (expect_true (SvMAGIC (sv)) \ + ? CORO_MAGIC_NN (sv, type) \ + : 0) -#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv) -#define CORO_MAGIC_state(sv) CORO_MAGIC (((SV *)(sv)), CORO_MAGIC_type_state) +#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv) +#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state) INLINE struct coro * SvSTATE_ (pTHX_ SV *coro) @@ -426,17 +463,8 @@ #define SvSTATE(sv) SvSTATE_ (aTHX_ (sv)) -/* fastert than SvSTATE, but expects a coroutine hv */ -INLINE struct coro * -SvSTATE_hv (SV *sv) -{ - MAGIC *mg = expect_true (SvMAGIC (sv)->mg_type == CORO_MAGIC_type_state) - ? SvMAGIC (sv) - : mg_find (sv, CORO_MAGIC_type_state); - - return (struct coro *)mg->mg_ptr; -} - +/* faster than SvSTATE, but expects a coroutine hv */ +#define SvSTATE_hv(hv) ((struct coro *)CORO_MAGIC_NN ((SV *)hv, CORO_MAGIC_type_state)->mg_ptr) #define SvSTATE_current SvSTATE_hv (SvRV (coro_current)) /* the next two functions merely cache the padlists */ @@ -453,12 +481,12 @@ #if CORO_PREFER_PERL_FUNCTIONS /* this is probably cleaner? but also slower! */ /* in practise, it seems to be less stable */ - CV *cp = Perl_cv_clone (cv); + CV *cp = Perl_cv_clone (aTHX_ cv); CvPADLIST (cv) = CvPADLIST (cp); CvPADLIST (cp) = 0; SvREFCNT_dec (cp); #else - CvPADLIST (cv) = coro_clone_padlist (aTHX_ cv); + CvPADLIST (cv) = coro_derive_padlist (aTHX_ cv); #endif } } @@ -515,12 +543,14 @@ PUTBACK; } - slf_frame = c->slf_frame; + slf_frame = c->slf_frame; + CORO_THROW = c->except; } static void save_perl (pTHX_ Coro__State c) { + c->except = CORO_THROW; c->slf_frame = slf_frame; { @@ -605,7 +635,7 @@ * not usually need a lot of stackspace. */ #if CORO_PREFER_PERL_FUNCTIONS -# define coro_init_stacks init_stacks +# define coro_init_stacks(thx) init_stacks () #else static void coro_init_stacks (pTHX) @@ -678,6 +708,15 @@ #endif } +#define CORO_RSS \ + rss += sizeof (SYM (curstackinfo)); \ + rss += (SYM (curstackinfo->si_cxmax) + 1) * sizeof (PERL_CONTEXT); \ + rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (SYM (curstack))) * sizeof (SV *); \ + rss += SYM (tmps_max) * sizeof (SV *); \ + rss += (SYM (markstack_max) - SYM (markstack_ptr)) * sizeof (I32); \ + rss += SYM (scopestack_max) * sizeof (I32); \ + rss += SYM (savestack_max) * sizeof (ANY); + static size_t coro_rss (pTHX_ struct coro *coro) { @@ -685,33 +724,17 @@ if (coro->mainstack) { - perl_slots tmp_slot; - perl_slots *slot; - if (coro->flags & CF_RUNNING) { - slot = &tmp_slot; - - #define VAR(name,type) slot->name = PL_ ## name; - # include "state.h" - #undef VAR + #define SYM(sym) PL_ ## sym + CORO_RSS; + #undef SYM } else - slot = coro->slot; - - if (slot) { - rss += sizeof (slot->curstackinfo); - rss += (slot->curstackinfo->si_cxmax + 1) * sizeof (PERL_CONTEXT); - rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (slot->curstack)) * sizeof (SV *); - rss += slot->tmps_max * sizeof (SV *); - rss += (slot->markstack_max - slot->markstack_ptr) * sizeof (I32); - rss += slot->scopestack_max * sizeof (I32); - rss += slot->savestack_max * sizeof (ANY); - -#if !PERL_VERSION_ATLEAST (5,10,0) - rss += slot->retstack_max * sizeof (OP *); -#endif + #define SYM(sym) coro->slot->sym + CORO_RSS; + #undef SYM } } @@ -823,7 +846,15 @@ return 0; } -static void +static int +slf_check_repeat (pTHX_ struct CoroSLF *frame) +{ + return 1; +} + +static UNOP coro_setup_op; + +static void NOINLINE /* noinline to keep it out of the transfer fast path */ coro_setup (pTHX_ struct coro *coro) { /* @@ -860,15 +891,15 @@ UNOP myop; Zero (&myop, 1, UNOP); - myop.op_next = Nullop; + myop.op_next = Nullop; + myop.op_type = OP_ENTERSUB; myop.op_flags = OPf_WANT_VOID; PUSHMARK (SP); - XPUSHs (sv_2mortal (av_shift (GvAV (PL_defgv)))); + PUSHs ((SV *)coro->startcv); PUTBACK; PL_op = (OP *)&myop; PL_op = PL_ppaddr[OP_ENTERSUB](aTHX); - SPAGAIN; } /* this newly created coroutine might be run on an existing cctx which most @@ -876,6 +907,17 @@ */ slf_frame.prepare = prepare_nop; /* provide a nop function for an eventual pp_slf */ slf_frame.check = slf_check_nop; /* signal pp_slf to not repeat */ + + /* and we have to provide the pp_slf op in any case, so pp_slf can skip it */ + coro_setup_op.op_next = PL_op; + coro_setup_op.op_type = OP_ENTERSUB; + coro_setup_op.op_ppaddr = pp_slf; + /* no flags etc. required, as an init function won't be called */ + + PL_op = (OP *)&coro_setup_op; + + /* copy throw, in case it was set before coro_setup */ + CORO_THROW = coro->except; } static void @@ -909,7 +951,9 @@ SvREFCNT_dec (PL_warnhook); SvREFCNT_dec (coro->saved_deffh); - SvREFCNT_dec (coro->throw); + SvREFCNT_dec (coro->rouse_cb); + SvREFCNT_dec (coro->invoke_cb); + SvREFCNT_dec (coro->invoke_av); coro_destruct_stacks (aTHX); } @@ -929,16 +973,14 @@ { COP *oldcop = 0; int oldcxix = -2; - struct coro *coro = SvSTATE_current; /* trace cctx is tied to specific coro */ - coro_cctx *cctx = coro->cctx; while ((PL_op = CALL_FPTR (PL_op->op_ppaddr) (aTHX))) { PERL_ASYNC_CHECK (); - if (cctx->flags & CC_TRACE_ALL) + if (cctx_current->flags & CC_TRACE_ALL) { - if (PL_op->op_type == OP_LEAVESUB && cctx->flags & CC_TRACE_SUB) + if (PL_op->op_type == OP_LEAVESUB && cctx_current->flags & CC_TRACE_SUB) { PERL_CONTEXT *cx = &cxstack[cxstack_ix]; SV **bot, **top; @@ -985,13 +1027,12 @@ { SV **cb; - if (oldcxix != cxstack_ix && cctx->flags & CC_TRACE_SUB) + if (oldcxix != cxstack_ix && cctx_current->flags & CC_TRACE_SUB) { PERL_CONTEXT *cx = &cxstack[cxstack_ix]; if (CxTYPE (cx) == CXt_SUB && oldcxix < cxstack_ix) { - runops_proc_t old_runops = PL_runops; dSP; GV *gv = CvGV (cx->blk_sub.cv); SV *fullname = sv_2mortal (newSV (0)); @@ -1006,7 +1047,7 @@ PUSHMARK (SP); PUSHs (&PL_sv_yes); PUSHs (fullname); - PUSHs (CxHASARGS (cx) ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef); + PUSHs (CxHASARGS (cx) ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef); PUTBACK; cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0); if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); @@ -1019,7 +1060,7 @@ oldcxix = cxstack_ix; } - if (cctx->flags & CC_TRACE_LINE) + if (cctx_current->flags & CC_TRACE_LINE) { dSP; @@ -1048,40 +1089,41 @@ return 0; } +static struct CoroSLF cctx_ssl_frame; + static void -prepare_set_stacklevel (struct coro_transfer_args *ta, struct coro_cctx *cctx) +slf_prepare_set_stacklevel (pTHX_ struct coro_transfer_args *ta) { - ta->prev = (struct coro *)cctx; - ta->next = 0; + ta->prev = 0; } -/* inject a fake call to Coro::State::_cctx_init into the execution */ -/* _cctx_init should be careful, as it could be called at almost any time */ -/* during execution of a perl program */ -/* also initialises PL_top_env */ -static void NOINLINE -cctx_prepare (pTHX_ coro_cctx *cctx) +static int +slf_check_set_stacklevel (pTHX_ struct CoroSLF *frame) { - dSP; - UNOP myop; + *frame = cctx_ssl_frame; + return frame->check (aTHX_ frame); /* execute the restored frame - there must be one */ +} + +/* initialises PL_top_env and injects a pseudo-slf-call to set the stacklevel */ +static void NOINLINE +cctx_prepare (pTHX) +{ PL_top_env = &PL_start_env; - if (cctx->flags & CC_TRACE) + if (cctx_current->flags & CC_TRACE) PL_runops = runops_trace; - Zero (&myop, 1, UNOP); - myop.op_next = PL_op; - myop.op_flags = OPf_WANT_VOID | OPf_STACKED; + /* we already must be executing an SLF op, there is no other valid way + * that can lead to creation of a new cctx */ + assert (("FATAL: can't prepare slf-less cctx in Coro module (please report)", + slf_frame.prepare && PL_op->op_ppaddr == pp_slf)); - PUSHMARK (SP); - EXTEND (SP, 2); - PUSHs (sv_2mortal (newSViv ((IV)cctx))); - PUSHs ((SV *)get_cv ("Coro::State::_cctx_init", FALSE)); - PUTBACK; - PL_op = (OP *)&myop; - PL_op = PL_ppaddr[OP_ENTERSUB](aTHX); - SPAGAIN; + /* we must emulate leaving pp_slf, which is done inside slf_check_set_stacklevel */ + cctx_ssl_frame = slf_frame; + + slf_frame.prepare = slf_prepare_set_stacklevel; + slf_frame.check = slf_check_set_stacklevel; } /* the tail of transfer: execute stuff we can only do after a transfer */ @@ -1110,7 +1152,7 @@ /* PL_nop = PL_nop->op_next */ /* inject a fake subroutine call to cctx_init */ - cctx_prepare (aTHX_ (coro_cctx *)arg); + cctx_prepare (aTHX); /* cctx_run is the alternative tail of transfer() */ transfer_tail (aTHX); @@ -1118,6 +1160,10 @@ /* somebody or something will hit me for both perl_run and PL_restartop */ PL_restartop = PL_op; perl_run (PL_curinterp); + /* + * Unfortunately, there is no way to get at the return values of the + * coro body here, as perl_run destroys these + */ /* * If perl-run returns we assume exit() was being called or the coro @@ -1211,6 +1257,8 @@ if (!cctx) return; + assert (cctx != cctx_current);//D temporary + --cctx_count; coro_destroy (&cctx->cctx); @@ -1278,6 +1326,8 @@ static void transfer_check (pTHX_ struct coro *prev, struct coro *next) { + /* TODO: throwing up here is considered harmful */ + if (expect_true (prev != next)) { if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW)))) @@ -1297,25 +1347,24 @@ } /* always use the TRANSFER macro */ -static void NOINLINE +static void NOINLINE /* noinline so we have a fixed stackframe */ transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx) { dSTACKLEVEL; /* sometimes transfer is only called to set idle_sp */ - if (expect_false (!next)) + if (expect_false (!prev)) { - ((coro_cctx *)prev)->idle_sp = (void *)stacklevel; - assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ + cctx_current->idle_sp = STACKLEVEL; + assert (cctx_current->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ } else if (expect_true (prev != next)) { - coro_cctx *prev__cctx; + coro_cctx *cctx_prev; if (expect_false (prev->flags & CF_NEW)) { /* create a new empty/source context */ - prev->cctx = cctx_new_empty (); prev->flags &= ~CF_NEW; prev->flags |= CF_RUNNING; } @@ -1336,39 +1385,40 @@ else load_perl (aTHX_ next); - prev__cctx = prev->cctx; - /* possibly untie and reuse the cctx */ if (expect_true ( - prev__cctx->idle_sp == (void *)stacklevel - && !(prev__cctx->flags & CC_TRACE) + cctx_current->idle_sp == STACKLEVEL + && !(cctx_current->flags & CC_TRACE) && !force_cctx )) { /* I assume that stacklevel is a stronger indicator than PL_top_env changes */ - assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == prev__cctx->idle_te)); - - prev->cctx = 0; + assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == cctx_current->idle_te)); /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get */ /* without this the next cctx_get might destroy the prev__cctx while still in use */ - if (expect_false (CCTX_EXPIRED (prev__cctx))) + if (expect_false (CCTX_EXPIRED (cctx_current))) if (!next->cctx) next->cctx = cctx_get (aTHX); - cctx_put (prev__cctx); + cctx_put (cctx_current); + assert (!prev->cctx);//D temporary } + else + prev->cctx = cctx_current; ++next->usecount; - if (expect_true (!next->cctx)) - next->cctx = cctx_get (aTHX); + cctx_prev = cctx_current; + cctx_current = expect_false (next->cctx) ? next->cctx : cctx_get (aTHX); + + next->cctx = 0; - if (expect_false (prev__cctx != next->cctx)) + if (expect_false (cctx_prev != cctx_current)) { - prev__cctx->top_env = PL_top_env; - PL_top_env = next->cctx->top_env; - coro_transfer (&prev__cctx->cctx, &next->cctx->cctx); + cctx_prev->top_env = PL_top_env; + PL_top_env = cctx_current->top_env; + coro_transfer (&cctx_prev->cctx, &cctx_current->cctx); } transfer_tail (aTHX); @@ -1417,7 +1467,9 @@ } cctx_destroy (coro->cctx); + SvREFCNT_dec (coro->startcv); SvREFCNT_dec (coro->args); + SvREFCNT_dec (CORO_THROW); if (coro->next) coro->next->prev = coro->prev; if (coro->prev) coro->prev->next = coro->next; @@ -1481,6 +1533,29 @@ TRANSFER (ta, 1); } +/*****************************************************************************/ +/* gensub: simple closure generation utility */ + +#define GENSUB_ARG CvXSUBANY (cv).any_ptr + +/* create a closure from XS, returns a code reference */ +/* the arg can be accessed via GENSUB_ARG from the callback */ +/* the callback must use dXSARGS/XSRETURN */ +static SV * +gensub (pTHX_ void (*xsub)(pTHX_ CV *), void *arg) +{ + CV *cv = (CV *)newSV (0); + + sv_upgrade ((SV *)cv, SVt_PVCV); + + CvANON_on (cv); + CvISXSUB_on (cv); + CvXSUB (cv) = xsub; + GENSUB_ARG = arg; + + return newRV_noinc ((SV *)cv); +} + /** Coro ********************************************************************/ INLINE void @@ -1533,8 +1608,7 @@ PUSHMARK (SP); PUTBACK; - call_sv (sv_hook, G_DISCARD); - SPAGAIN; + call_sv (sv_hook, G_VOID | G_DISCARD); FREETMPS; LEAVE; @@ -1552,18 +1626,49 @@ return !!(SvSTATE (coro_sv)->flags & CF_READY); } +/* expects to own a reference to next->hv */ INLINE void -prepare_schedule (pTHX_ struct coro_transfer_args *ta) +prepare_schedule_to (pTHX_ struct coro_transfer_args *ta, struct coro *next) { - SV *prev_sv, *next_sv; + SV *prev_sv = SvRV (coro_current); + + ta->prev = SvSTATE_hv (prev_sv); + ta->next = next; + + TRANSFER_CHECK (*ta); + + SvRV_set (coro_current, (SV *)next->hv); + + free_coro_mortal (aTHX); + coro_mortal = prev_sv; +} +static void +prepare_schedule (pTHX_ struct coro_transfer_args *ta) +{ for (;;) { - next_sv = coro_deq (aTHX); + SV *next_sv = coro_deq (aTHX); + + if (expect_true (next_sv)) + { + struct coro *next = SvSTATE_hv (next_sv); + + /* cannot transfer to destroyed coros, skip and look for next */ + if (expect_false (next->flags & CF_DESTROYED)) + SvREFCNT_dec (next_sv); /* coro_nready has already been taken care of by destroy */ + else + { + next->flags &= ~CF_READY; + --coro_nready; - /* nothing to schedule: call the idle handler */ - if (expect_false (!next_sv)) + prepare_schedule_to (aTHX_ ta, next); + break; + } + } + else { + /* nothing to schedule: call the idle handler */ dSP; ENTER; @@ -1571,38 +1676,12 @@ PUSHMARK (SP); PUTBACK; - call_sv (get_sv ("Coro::idle", FALSE), G_DISCARD); - SPAGAIN; + call_sv (get_sv ("Coro::idle", FALSE), G_VOID | G_DISCARD); FREETMPS; LEAVE; - continue; } - - ta->next = SvSTATE_hv (next_sv); - - /* cannot transfer to destroyed coros, skip and look for next */ - if (expect_false (ta->next->flags & CF_DESTROYED)) - { - SvREFCNT_dec (next_sv); - /* coro_nready has already been taken care of by destroy */ - continue; - } - - --coro_nready; - break; } - - /* free this only after the transfer */ - prev_sv = SvRV (coro_current); - ta->prev = SvSTATE_hv (prev_sv); - TRANSFER_CHECK (*ta); - assert (("FATAL: next coroutine isn't marked as ready in Coro (please report)", ta->next->flags & CF_READY)); - ta->next->flags &= ~CF_READY; - SvRV_set (coro_current, next_sv); - - free_coro_mortal (aTHX); - coro_mortal = prev_sv; } INLINE void @@ -1635,6 +1714,16 @@ TRANSFER (ta, 1); } +static void +api_schedule_to (pTHX_ SV *coro_sv) +{ + struct coro_transfer_args ta; + struct coro *next = SvSTATE (coro_sv); + + SvREFCNT_inc_NN (coro_sv); + prepare_schedule_to (aTHX_ &ta, next); +} + static int api_cede (pTHX) { @@ -1691,89 +1780,253 @@ } } +static void +coro_call_on_destroy (pTHX_ struct coro *coro) +{ + SV **on_destroyp = hv_fetch (coro->hv, "_on_destroy", sizeof ("_on_destroy") - 1, 0); + SV **statusp = hv_fetch (coro->hv, "_status", sizeof ("_status") - 1, 0); + + if (on_destroyp) + { + AV *on_destroy = (AV *)SvRV (*on_destroyp); + + while (AvFILLp (on_destroy) >= 0) + { + dSP; /* don't disturb outer sp */ + SV *cb = av_pop (on_destroy); + + PUSHMARK (SP); + + if (statusp) + { + int i; + AV *status = (AV *)SvRV (*statusp); + EXTEND (SP, AvFILLp (status) + 1); + + for (i = 0; i <= AvFILLp (status); ++i) + PUSHs (AvARRAY (status)[i]); + } + + PUTBACK; + call_sv (sv_2mortal (cb), G_VOID | G_DISCARD); + } + } +} + +static void +slf_init_terminate (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + int i; + HV *hv = (HV *)SvRV (coro_current); + AV *av = newAV (); + + av_extend (av, items - 1); + for (i = 0; i < items; ++i) + av_push (av, SvREFCNT_inc_NN (arg [i])); + + hv_store (hv, "_status", sizeof ("_status") - 1, newRV_noinc ((SV *)av), 0); + + av_push (av_destroy, (SV *)newRV_inc ((SV *)hv)); /* RVinc for perl */ + api_ready (aTHX_ sv_manager); + + frame->prepare = prepare_schedule; + frame->check = slf_check_repeat; +} + /*****************************************************************************/ -/* PerlIO::cede */ +/* async pool handler */ -typedef struct +static int +slf_check_pool_handler (pTHX_ struct CoroSLF *frame) { - PerlIOBuf base; - NV next, every; -} PerlIOCede; + HV *hv = (HV *)SvRV (coro_current); + struct coro *coro = (struct coro *)frame->data; -static IV -PerlIOCede_pushed (pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab) + if (!coro->invoke_cb) + return 1; /* loop till we have invoke */ + else + { + hv_store (hv, "desc", sizeof ("desc") - 1, + newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0); + + coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv); + + { + dSP; + XPUSHs (sv_2mortal (coro->invoke_cb)); coro->invoke_cb = 0; + PUTBACK; + } + + SvREFCNT_dec (GvAV (PL_defgv)); + GvAV (PL_defgv) = coro->invoke_av; + coro->invoke_av = 0; + + return 0; + } +} + +static void +slf_init_pool_handler (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) { - PerlIOCede *self = PerlIOSelf (f, PerlIOCede); + HV *hv = (HV *)SvRV (coro_current); + struct coro *coro = SvSTATE_hv ((SV *)hv); - self->every = SvCUR (arg) ? SvNV (arg) : 0.01; - self->next = nvtime () + self->every; + if (expect_true (coro->saved_deffh)) + { + /* subsequent iteration */ + SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh; + coro->saved_deffh = 0; - return PerlIOBuf_pushed (aTHX_ f, mode, Nullsv, tab); + if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss) + || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size)) + { + coro->invoke_cb = SvREFCNT_inc_NN ((SV *)cv_coro_terminate); + coro->invoke_av = newAV (); + + frame->prepare = prepare_nop; + } + else + { + av_clear (GvAV (PL_defgv)); + hv_store (hv, "desc", sizeof ("desc") - 1, SvREFCNT_inc_NN (sv_async_pool_idle), 0); + + coro->prio = 0; + + if (coro->cctx && (coro->cctx->flags & CC_TRACE)) + api_trace (aTHX_ coro_current, 0); + + frame->prepare = prepare_schedule; + av_push (av_async_pool, SvREFCNT_inc (hv)); + } + } + else + { + /* first iteration, simply fall through */ + frame->prepare = prepare_nop; + } + + frame->check = slf_check_pool_handler; + frame->data = (void *)coro; } -static SV * -PerlIOCede_getarg (pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags) +/*****************************************************************************/ +/* rouse callback */ + +#define CORO_MAGIC_type_rouse PERL_MAGIC_ext + +static void +coro_rouse_callback (pTHX_ CV *cv) { - PerlIOCede *self = PerlIOSelf (f, PerlIOCede); + dXSARGS; + SV *data = (SV *)GENSUB_ARG; - return newSVnv (self->every); + if (SvTYPE (SvRV (data)) != SVt_PVAV) + { + /* first call, set args */ + AV *av = newAV (); + SV *coro = SvRV (data); + + SvRV_set (data, (SV *)av); + api_ready (aTHX_ coro); + SvREFCNT_dec (coro); + + /* better take a full copy of the arguments */ + while (items--) + av_store (av, items, newSVsv (ST (items))); + } + + XSRETURN_EMPTY; } -static IV -PerlIOCede_flush (pTHX_ PerlIO *f) +static int +slf_check_rouse_wait (pTHX_ struct CoroSLF *frame) { - PerlIOCede *self = PerlIOSelf (f, PerlIOCede); - double now = nvtime (); + SV *data = (SV *)frame->data; + + if (CORO_THROW) + return 0; - if (now >= self->next) + if (SvTYPE (SvRV (data)) != SVt_PVAV) + return 1; + + /* now push all results on the stack */ + { + dSP; + AV *av = (AV *)SvRV (data); + int i; + + EXTEND (SP, AvFILLp (av) + 1); + for (i = 0; i <= AvFILLp (av); ++i) + PUSHs (sv_2mortal (AvARRAY (av)[i])); + + /* we have stolen the elements, so ste length to zero and free */ + AvFILLp (av) = -1; + av_undef (av); + + PUTBACK; + } + + return 0; +} + +static void +slf_init_rouse_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + SV *cb; + + if (items) + cb = arg [0]; + else { - api_cede (aTHX); - self->next = now + self->every; + struct coro *coro = SvSTATE_current; + + if (!coro->rouse_cb) + croak ("Coro::rouse_wait called without rouse callback, and no default rouse callback found either,"); + + cb = sv_2mortal (coro->rouse_cb); + coro->rouse_cb = 0; } - return PerlIOBuf_flush (aTHX_ f); + if (!SvROK (cb) + || SvTYPE (SvRV (cb)) != SVt_PVCV + || CvXSUB ((CV *)SvRV (cb)) != coro_rouse_callback) + croak ("Coro::rouse_wait called with illegal callback argument,"); + + { + CV *cv = (CV *)SvRV (cb); /* for GENSUB_ARG */ + SV *data = (SV *)GENSUB_ARG; + + frame->data = (void *)data; + frame->prepare = SvTYPE (SvRV (data)) == SVt_PVAV ? prepare_nop : prepare_schedule; + frame->check = slf_check_rouse_wait; + } } -static PerlIO_funcs PerlIO_cede = +static SV * +coro_new_rouse_cb (pTHX) { - sizeof(PerlIO_funcs), - "cede", - sizeof(PerlIOCede), - PERLIO_K_DESTRUCT | PERLIO_K_RAW, - PerlIOCede_pushed, - PerlIOBuf_popped, - PerlIOBuf_open, - PerlIOBase_binmode, - PerlIOCede_getarg, - PerlIOBase_fileno, - PerlIOBuf_dup, - PerlIOBuf_read, - PerlIOBuf_unread, - PerlIOBuf_write, - PerlIOBuf_seek, - PerlIOBuf_tell, - PerlIOBuf_close, - PerlIOCede_flush, - PerlIOBuf_fill, - PerlIOBase_eof, - PerlIOBase_error, - PerlIOBase_clearerr, - PerlIOBase_setlinebuf, - PerlIOBuf_get_base, - PerlIOBuf_bufsiz, - PerlIOBuf_get_ptr, - PerlIOBuf_get_cnt, - PerlIOBuf_set_ptrcnt, -}; + HV *hv = (HV *)SvRV (coro_current); + struct coro *coro = SvSTATE_hv (hv); + SV *data = newRV_inc ((SV *)hv); + SV *cb = gensub (aTHX_ coro_rouse_callback, (void *)data); -/*****************************************************************************/ + sv_magicext (SvRV (cb), data, CORO_MAGIC_type_rouse, 0, 0, 0); + SvREFCNT_dec (data); /* magicext increases the refcount */ + + SvREFCNT_dec (coro->rouse_cb); + coro->rouse_cb = SvREFCNT_inc_NN (cb); + + return cb; +} -static const CV *slf_cv; /* for quick consistency check */ +/*****************************************************************************/ +/* schedule-like-function opcode (SLF) */ static UNOP slf_restore; /* restore stack as entersub did, for first-re-run */ -static SV *slf_arg0; -static SV *slf_arg1; -static SV *slf_arg2; +static const CV *slf_cv; +static SV **slf_argv; +static int slf_argc, slf_arga; /* count, allocated */ +static I32 slf_ax; /* top of stack, for restore */ /* this restores the stack in the case we patched the entersub, to */ /* recreate the stack frame as perl will on following calls */ @@ -1781,33 +2034,19 @@ static OP * pp_restore (pTHX) { - dSP; + int i; + SV **SP = PL_stack_base + slf_ax; PUSHMARK (SP); - EXTEND (SP, 3); - if (slf_arg0) PUSHs (sv_2mortal (slf_arg0)); - if (slf_arg1) PUSHs (sv_2mortal (slf_arg1)); - if (slf_arg2) PUSHs (sv_2mortal (slf_arg2)); - PUSHs ((SV *)CvGV (slf_cv)); + EXTEND (SP, slf_argc + 1); - RETURNOP (slf_restore.op_first); -} - -static void -slf_prepare_set_stacklevel (pTHX_ struct coro_transfer_args *ta) -{ - prepare_set_stacklevel (ta, (struct coro_cctx *)slf_frame.data); -} + for (i = 0; i < slf_argc; ++i) + PUSHs (sv_2mortal (slf_argv [i])); -static void -slf_init_set_stacklevel (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) -{ - assert (("FATAL: set_stacklevel needs the coro cctx as sole argument", items == 1)); + PUSHs ((SV *)CvGV (slf_cv)); - frame->prepare = slf_prepare_set_stacklevel; - frame->check = slf_check_nop; - frame->data = (void *)SvIV (arg [0]); + RETURNOP (slf_restore.op_first); } static void @@ -1816,17 +2055,6 @@ SV **arg = (SV **)slf_frame.data; prepare_transfer (aTHX_ ta, arg [0], arg [1]); - - /* if the destination has ->throw set, then copy it */ - /* into the current coro's throw slot, so it will be raised */ - /* after the schedule */ - if (expect_false (ta->next->throw)) - { - struct coro *coro = SvSTATE_current; - SvREFCNT_dec (coro->throw); - coro->throw = ta->next->throw; - ta->next->throw = 0; - } } static void @@ -1848,6 +2076,34 @@ } static void +slf_prepare_schedule_to (pTHX_ struct coro_transfer_args *ta) +{ + struct coro *next = (struct coro *)slf_frame.data; + + SvREFCNT_inc_NN (next->hv); + prepare_schedule_to (aTHX_ ta, next); +} + +static void +slf_init_schedule_to (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + if (!items) + croak ("Coro::schedule_to expects a coroutine argument, caught"); + + frame->data = (void *)SvSTATE (arg [0]); + frame->prepare = slf_prepare_schedule_to; + frame->check = slf_check_nop; +} + +static void +slf_init_cede_to (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + api_ready (aTHX_ SvRV (coro_current)); + + slf_init_schedule_to (aTHX_ frame, cv, arg, items); +} + +static void slf_init_cede (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) { frame->prepare = prepare_cede; @@ -1861,9 +2117,6 @@ frame->check = slf_check_nop; } -/* we hijack an hopefully unused CV flag for our purposes */ -#define CVf_SLF 0x4000 - /* * these not obviously related functions are all rolled into one * function to increase chances that they all will call transfer with the same @@ -1888,7 +2141,9 @@ /* do a quick consistency check on the "function" object, and if it isn't */ /* for us, divert to the real entersub */ - if (SvTYPE (gv) != SVt_PVGV || !(CvFLAGS (GvCV (gv)) & CVf_SLF)) + if (SvTYPE (gv) != SVt_PVGV + || !GvCV (gv) + || !(CvFLAGS (GvCV (gv)) & CVf_SLF)) return PL_ppaddr[OP_ENTERSUB](aTHX); if (!(PL_op->op_flags & OPf_STACKED)) @@ -1899,8 +2154,6 @@ items = AvFILLp (av) + 1; } - PUTBACK; - /* now call the init function, which needs to set up slf_frame */ ((coro_slf_cb)CvXSUBANY (GvCV (gv)).any_ptr) (aTHX_ &slf_frame, GvCV (gv), arg, items); @@ -1926,53 +2179,51 @@ } while (slf_frame.check (aTHX_ &slf_frame)); - { - dSP; - SV **bot = PL_stack_base + checkmark; - int gimme = GIMME_V; + slf_frame.prepare = 0; /* invalidate the frame, we are done processing it */ - slf_frame.prepare = 0; /* invalidate the frame, so it gets initialised again next time */ + /* exception handling */ + if (expect_false (CORO_THROW)) + { + SV *exception = sv_2mortal (CORO_THROW); - /* make sure we put something on the stack in scalar context */ - if (gimme == G_SCALAR) - { - if (sp == bot) - XPUSHs (&PL_sv_undef); + CORO_THROW = 0; + sv_setsv (ERRSV, exception); + croak (0); + } - SP = bot + 1; - } + /* return value handling - mostly like entersub */ + /* make sure we put something on the stack in scalar context */ + if (GIMME_V == G_SCALAR) + { + dSP; + SV **bot = PL_stack_base + checkmark; - PUTBACK; - } + if (sp == bot) /* too few, push undef */ + bot [1] = &PL_sv_undef; + else if (sp != bot + 1) /* too many, take last one */ + bot [1] = *sp; - { - struct coro *coro = SvSTATE_current; + SP = bot + 1; - if (expect_false (coro->throw)) - { - SV *exception = sv_2mortal (coro->throw); - - coro->throw = 0; - sv_setsv (ERRSV, exception); - croak (0); - } - } + PUTBACK; + } return NORMAL; } static void -api_execute_slf (pTHX_ CV *cv, coro_slf_cb init_cb, SV **arg, int items) +api_execute_slf (pTHX_ CV *cv, coro_slf_cb init_cb, I32 ax) { + int i; + SV **arg = PL_stack_base + ax; + int items = PL_stack_sp - arg + 1; + assert (("FATAL: SLF call with illegal CV value", !CvANON (cv))); if (PL_op->op_ppaddr != PL_ppaddr [OP_ENTERSUB] && PL_op->op_ppaddr != pp_slf) croak ("FATAL: Coro SLF calls can only be made normally, not via goto or any other means, caught"); - if (items > 3) - croak ("Coro only supports up to three arguments to SLF functions currently (not %d), caught", items); - CvFLAGS (cv) |= CVf_SLF; CvXSUBANY (cv).any_ptr = (void *)init_cb; slf_cv = cv; @@ -1980,21 +2231,134 @@ /* we patch the op, and then re-run the whole call */ /* we have to put the same argument on the stack for this to work */ /* and this will be done by pp_restore */ - slf_restore.op_next = (OP *)&slf_restore; - slf_restore.op_type = OP_CUSTOM; + slf_restore.op_next = (OP *)&slf_restore; + slf_restore.op_type = OP_CUSTOM; slf_restore.op_ppaddr = pp_restore; - slf_restore.op_first = PL_op; + slf_restore.op_first = PL_op; + + slf_ax = ax - 1; /* undo the ax++ inside dAXMARK */ + + if (PL_op->op_flags & OPf_STACKED) + { + if (items > slf_arga) + { + slf_arga = items; + free (slf_argv); + slf_argv = malloc (slf_arga * sizeof (SV *)); + } - slf_arg0 = items > 0 ? SvREFCNT_inc (arg [0]) : 0; - slf_arg1 = items > 1 ? SvREFCNT_inc (arg [1]) : 0; - slf_arg2 = items > 2 ? SvREFCNT_inc (arg [2]) : 0; + slf_argc = items; + + for (i = 0; i < items; ++i) + slf_argv [i] = SvREFCNT_inc (arg [i]); + } + else + slf_argc = 0; PL_op->op_ppaddr = pp_slf; + /*PL_op->op_type = OP_CUSTOM; /* we do behave like entersub still */ PL_op = (OP *)&slf_restore; } /*****************************************************************************/ +/* PerlIO::cede */ + +typedef struct +{ + PerlIOBuf base; + NV next, every; +} PerlIOCede; + +static IV +PerlIOCede_pushed (pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab) +{ + PerlIOCede *self = PerlIOSelf (f, PerlIOCede); + + self->every = SvCUR (arg) ? SvNV (arg) : 0.01; + self->next = nvtime () + self->every; + + return PerlIOBuf_pushed (aTHX_ f, mode, Nullsv, tab); +} + +static SV * +PerlIOCede_getarg (pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags) +{ + PerlIOCede *self = PerlIOSelf (f, PerlIOCede); + + return newSVnv (self->every); +} + +static IV +PerlIOCede_flush (pTHX_ PerlIO *f) +{ + PerlIOCede *self = PerlIOSelf (f, PerlIOCede); + double now = nvtime (); + + if (now >= self->next) + { + api_cede (aTHX); + self->next = now + self->every; + } + + return PerlIOBuf_flush (aTHX_ f); +} + +static PerlIO_funcs PerlIO_cede = +{ + sizeof(PerlIO_funcs), + "cede", + sizeof(PerlIOCede), + PERLIO_K_DESTRUCT | PERLIO_K_RAW, + PerlIOCede_pushed, + PerlIOBuf_popped, + PerlIOBuf_open, + PerlIOBase_binmode, + PerlIOCede_getarg, + PerlIOBase_fileno, + PerlIOBuf_dup, + PerlIOBuf_read, + PerlIOBuf_unread, + PerlIOBuf_write, + PerlIOBuf_seek, + PerlIOBuf_tell, + PerlIOBuf_close, + PerlIOCede_flush, + PerlIOBuf_fill, + PerlIOBase_eof, + PerlIOBase_error, + PerlIOBase_clearerr, + PerlIOBase_setlinebuf, + PerlIOBuf_get_base, + PerlIOBuf_bufsiz, + PerlIOBuf_get_ptr, + PerlIOBuf_get_cnt, + PerlIOBuf_set_ptrcnt, +}; + +/*****************************************************************************/ +/* Coro::Semaphore & Coro::Signal */ + +static SV * +coro_waitarray_new (pTHX_ int count) +{ + /* a semaphore contains a counter IV in $sem->[0] and any waiters after that */ + AV *av = newAV (); + SV **ary; + + /* unfortunately, building manually saves memory */ + Newx (ary, 2, SV *); + AvALLOC (av) = ary; + /*AvARRAY (av) = ary;*/ + SvPVX ((SV *)av) = (char *)ary; /* 5.8.8 needs this syntax instead of AvARRAY = ary */ + AvMAX (av) = 1; + AvFILLp (av) = 0; + ary [0] = newSViv (count); + + return newRV_noinc ((SV *)av); +} + +/* semaphore */ static void coro_semaphore_adjust (pTHX_ AV *av, IV adjust) @@ -2016,13 +2380,20 @@ cb = av_shift (av); if (SvOBJECT (cb)) - api_ready (aTHX_ cb); - else - croak ("callbacks not yet supported"); + { + api_ready (aTHX_ cb); + --count; + } + else if (SvTYPE (cb) == SVt_PVCV) + { + dSP; + PUSHMARK (SP); + XPUSHs (sv_2mortal (newRV_inc ((SV *)av))); + PUTBACK; + call_sv (cb, G_VOID | G_DISCARD | G_EVAL | G_KEEPERR); + } SvREFCNT_dec (cb); - - --count; } } @@ -2034,15 +2405,23 @@ } static int -slf_check_semaphore_down (pTHX_ struct CoroSLF *frame) +slf_check_semaphore_down_or_wait (pTHX_ struct CoroSLF *frame, int acquire) { AV *av = (AV *)frame->data; SV *count_sv = AvARRAY (av)[0]; - if (SvIVX (count_sv) > 0) + /* if we are about to throw, don't actually acquire the lock, just throw */ + if (CORO_THROW) + return 0; + else if (SvIVX (count_sv) > 0) { SvSTATE_current->on_destroy = 0; - SvIVX (count_sv) = SvIVX (count_sv) - 1; + + if (acquire) + SvIVX (count_sv) = SvIVX (count_sv) - 1; + else + coro_semaphore_adjust (aTHX_ av, 0); + return 0; } else @@ -2061,8 +2440,20 @@ } } +static int +slf_check_semaphore_down (pTHX_ struct CoroSLF *frame) +{ + return slf_check_semaphore_down_or_wait (aTHX_ frame, 1); +} + +static int +slf_check_semaphore_wait (pTHX_ struct CoroSLF *frame) +{ + return slf_check_semaphore_down_or_wait (aTHX_ frame, 0); +} + static void -slf_init_semaphore_down (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +slf_init_semaphore_down_or_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) { AV *av = (AV *)SvRV (arg [0]); @@ -2070,7 +2461,6 @@ { frame->data = (void *)av; frame->prepare = prepare_nop; - SvSTATE_current->on_destroy = coro_semaphore_on_destroy; } else { @@ -2081,38 +2471,269 @@ /* to avoid race conditions when a woken-up coro gets terminated */ /* we arrange for a temporary on_destroy that calls adjust (0) */ - assert (!SvSTATE_current->on_destroy);//D SvSTATE_current->on_destroy = coro_semaphore_on_destroy; } +} +static void +slf_init_semaphore_down (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + slf_init_semaphore_down_or_wait (aTHX_ frame, cv, arg, items); frame->check = slf_check_semaphore_down; +} + +static void +slf_init_semaphore_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + if (items >= 2) + { + /* callback form */ + AV *av = (AV *)SvRV (arg [0]); + CV *cb_cv = coro_sv_2cv (aTHX_ arg [1]); + + av_push (av, (SV *)SvREFCNT_inc_NN (cb_cv)); + + if (SvIVX (AvARRAY (av)[0]) > 0) + coro_semaphore_adjust (aTHX_ av, 0); + + frame->prepare = prepare_nop; + frame->check = slf_check_nop; + } + else + { + slf_init_semaphore_down_or_wait (aTHX_ frame, cv, arg, items); + frame->check = slf_check_semaphore_wait; + } +} + +/* signal */ + +static void +coro_signal_wake (pTHX_ AV *av, int count) +{ + SvIVX (AvARRAY (av)[0]) = 0; + + /* now signal count waiters */ + while (count > 0 && AvFILLp (av) > 0) + { + SV *cb; + + /* swap first two elements so we can shift a waiter */ + cb = AvARRAY (av)[0]; + AvARRAY (av)[0] = AvARRAY (av)[1]; + AvARRAY (av)[1] = cb; + + cb = av_shift (av); + + api_ready (aTHX_ cb); + sv_setiv (cb, 0); /* signal waiter */ + SvREFCNT_dec (cb); + + --count; + } +} + +static int +slf_check_signal_wait (pTHX_ struct CoroSLF *frame) +{ + /* if we are about to throw, also stop waiting */ + return SvROK ((SV *)frame->data) && !CORO_THROW; +} + +static void +slf_init_signal_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + AV *av = (AV *)SvRV (arg [0]); + + if (SvIVX (AvARRAY (av)[0])) + { + SvIVX (AvARRAY (av)[0]) = 0; + frame->prepare = prepare_nop; + frame->check = slf_check_nop; + } + else + { + SV *waiter = newRV_inc (SvRV (coro_current)); /* owned by signal av */ + av_push (av, waiter); + + frame->data = (void *)sv_2mortal (SvREFCNT_inc_NN (waiter)); /* owned by process */ + frame->prepare = prepare_schedule; + frame->check = slf_check_signal_wait; + } } /*****************************************************************************/ +/* Coro::AIO */ -#define GENSUB_ARG CvXSUBANY (cv).any_ptr +#define CORO_MAGIC_type_aio PERL_MAGIC_ext -/* create a closure from XS, returns a code reference */ -/* the arg can be accessed via GENSUB_ARG from the callback */ -/* the callback must use dXSARGS/XSRETURN */ -static SV * -gensub (pTHX_ void (*xsub)(pTHX_ CV *), void *arg) +/* helper storage struct */ +struct io_state { - CV *cv = (CV *)NEWSV (0, 0); + int errorno; + I32 laststype; /* U16 in 5.10.0 */ + int laststatval; + Stat_t statcache; +}; - sv_upgrade ((SV *)cv, SVt_PVCV); +static void +coro_aio_callback (pTHX_ CV *cv) +{ + dXSARGS; + AV *state = (AV *)GENSUB_ARG; + SV *coro = av_pop (state); + SV *data_sv = newSV (sizeof (struct io_state)); + + av_extend (state, items - 1); + + sv_upgrade (data_sv, SVt_PV); + SvCUR_set (data_sv, sizeof (struct io_state)); + SvPOK_only (data_sv); - CvANON_on (cv); - CvISXSUB_on (cv); - CvXSUB (cv) = xsub; - GENSUB_ARG = arg; + { + struct io_state *data = (struct io_state *)SvPVX (data_sv); - return newRV_noinc ((SV *)cv); + data->errorno = errno; + data->laststype = PL_laststype; + data->laststatval = PL_laststatval; + data->statcache = PL_statcache; + } + + /* now build the result vector out of all the parameters and the data_sv */ + { + int i; + + for (i = 0; i < items; ++i) + av_push (state, SvREFCNT_inc_NN (ST (i))); + } + + av_push (state, data_sv); + + api_ready (aTHX_ coro); + SvREFCNT_dec (coro); + SvREFCNT_dec ((AV *)state); +} + +static int +slf_check_aio_req (pTHX_ struct CoroSLF *frame) +{ + AV *state = (AV *)frame->data; + + /* if we are about to throw, return early */ + /* this does not cancel the aio request, but at least */ + /* it quickly returns */ + if (CORO_THROW) + return 0; + + /* one element that is an RV? repeat! */ + if (AvFILLp (state) == 0 && SvROK (AvARRAY (state)[0])) + return 1; + + /* restore status */ + { + SV *data_sv = av_pop (state); + struct io_state *data = (struct io_state *)SvPVX (data_sv); + + errno = data->errorno; + PL_laststype = data->laststype; + PL_laststatval = data->laststatval; + PL_statcache = data->statcache; + + SvREFCNT_dec (data_sv); + } + + /* push result values */ + { + dSP; + int i; + + EXTEND (SP, AvFILLp (state) + 1); + for (i = 0; i <= AvFILLp (state); ++i) + PUSHs (sv_2mortal (SvREFCNT_inc_NN (AvARRAY (state)[i]))); + + PUTBACK; + } + + return 0; +} + +static void +slf_init_aio_req (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + AV *state = (AV *)sv_2mortal ((SV *)newAV ()); + SV *coro_hv = SvRV (coro_current); + struct coro *coro = SvSTATE_hv (coro_hv); + + /* put our coroutine id on the state arg */ + av_push (state, SvREFCNT_inc_NN (coro_hv)); + + /* first see whether we have a non-zero priority and set it as AIO prio */ + if (coro->prio) + { + dSP; + + static SV *prio_cv; + static SV *prio_sv; + + if (expect_false (!prio_cv)) + { + prio_cv = (SV *)get_cv ("IO::AIO::aioreq_pri", 0); + prio_sv = newSViv (0); + } + + PUSHMARK (SP); + sv_setiv (prio_sv, coro->prio); + XPUSHs (prio_sv); + + PUTBACK; + call_sv (prio_cv, G_VOID | G_DISCARD); + } + + /* now call the original request */ + { + dSP; + CV *req = (CV *)CORO_MAGIC_NN ((SV *)cv, CORO_MAGIC_type_aio)->mg_obj; + int i; + + PUSHMARK (SP); + + /* first push all args to the stack */ + EXTEND (SP, items + 1); + + for (i = 0; i < items; ++i) + PUSHs (arg [i]); + + /* now push the callback closure */ + PUSHs (sv_2mortal (gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state)))); + + /* now call the AIO function - we assume our request is uncancelable */ + PUTBACK; + call_sv ((SV *)req, G_VOID | G_DISCARD); + } + + /* now that the requets is going, we loop toll we have a result */ + frame->data = (void *)state; + frame->prepare = prepare_schedule; + frame->check = slf_check_aio_req; +} + +static void +coro_aio_req_xs (pTHX_ CV *cv) +{ + dXSARGS; + + CORO_EXECUTE_SLF_XS (slf_init_aio_req); + + XSRETURN_EMPTY; } /*****************************************************************************/ +#if CORO_CLONE +# include "clone.c" +#endif + MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_ PROTOTYPES: DISABLE @@ -2126,6 +2747,8 @@ #endif BOOT_PAGESIZE; + cctx_current = cctx_new_empty (); + irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV); stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO); @@ -2154,12 +2777,10 @@ SV *slf = sv_2mortal (newSViv (PTR2IV (pp_slf))); if (!PL_custom_op_names) PL_custom_op_names = newHV (); - hv_store_ent (PL_custom_op_names, slf, - newSVpv ("coro_slf", 0), 0); + hv_store_ent (PL_custom_op_names, slf, newSVpv ("coro_slf", 0), 0); if (!PL_custom_op_descs) PL_custom_op_descs = newHV (); - hv_store_ent (PL_custom_op_descs, slf, - newSVpv ("coro schedule like function", 0), 0); + hv_store_ent (PL_custom_op_descs, slf, newSVpv ("coro schedule like function", 0), 0); } coroapi.ver = CORO_API_VERSION; @@ -2188,13 +2809,30 @@ SV * new (char *klass, ...) + ALIAS: + Coro::new = 1 CODE: { struct coro *coro; MAGIC *mg; HV *hv; + CV *cb; int i; + if (items > 1) + { + cb = coro_sv_2cv (aTHX_ ST (1)); + + if (!ix) + { + if (CvISXSUB (cb)) + croak ("Coro::State doesn't support XS functions as coroutine start, caught"); + + if (!CvROOT (cb)) + croak ("Coro::State doesn't support autoloaded or undefined functions as coroutine start, caught"); + } + } + Newz (0, coro, 1, struct coro); coro->args = newAV (); coro->flags = CF_NEW; @@ -2208,23 +2846,30 @@ mg->mg_flags |= MGf_DUP; RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1)); - av_extend (coro->args, items - 1); - for (i = 1; i < items; i++) - av_push (coro->args, newSVsv (ST (i))); + if (items > 1) + { + av_extend (coro->args, items - 1 + ix - 1); + + if (ix) + { + av_push (coro->args, SvREFCNT_inc_NN ((SV *)cb)); + cb = cv_coro_run; + } + + coro->startcv = (CV *)SvREFCNT_inc_NN ((SV *)cb); + + for (i = 2; i < items; i++) + av_push (coro->args, newSVsv (ST (i))); + } } OUTPUT: RETVAL void -_set_stacklevel (...) - CODE: - api_execute_slf (aTHX_ cv, slf_init_set_stacklevel, &ST (0), items); - -void transfer (...) PROTOTYPE: $$ CODE: - api_execute_slf (aTHX_ cv, slf_init_transfer, &ST (0), items); + CORO_EXECUTE_SLF_XS (slf_init_transfer); bool _destroy (SV *coro_sv) @@ -2239,6 +2884,25 @@ CODE: _exit (code); +SV * +clone (Coro::State coro) + CODE: +{ +#if CORO_CLONE + struct coro *ncoro = coro_clone (coro); + MAGIC *mg; + /* TODO: too much duplication */ + ncoro->hv = newHV (); + mg = sv_magicext ((SV *)ncoro->hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)ncoro, 0); + mg->mg_flags |= MGf_DUP; + RETVAL = sv_bless (newRV_noinc ((SV *)ncoro->hv), SvSTASH (coro->hv)); +#else + croak ("Coro::State->clone has not been configured into this installation of Coro, realised"); +#endif +} + OUTPUT: + RETVAL + int cctx_stacksize (int new_stacksize = 0) PROTOTYPE: ;$ @@ -2352,8 +3016,12 @@ throw (Coro::State self, SV *throw = &PL_sv_undef) PROTOTYPE: $;$ CODE: - SvREFCNT_dec (self->throw); - self->throw = SvOK (throw) ? newSVsv (throw) : 0; +{ + struct coro *current = SvSTATE_current; + SV **throwp = self == current ? &CORO_THROW : &self->except; + SvREFCNT_dec (*throwp); + *throwp = SvOK (throw) ? newSVsv (throw) : 0; +} void api_trace (SV *coro, int flags = CC_TRACE | CC_TRACE_SUB) @@ -2364,7 +3032,8 @@ has_cctx (Coro::State coro) PROTOTYPE: $ CODE: - RETVAL = boolSV (!!coro->cctx); + /* maybe manage the running flag differently */ + RETVAL = boolSV (!!coro->cctx || (coro->flags & CF_RUNNING)); OUTPUT: RETVAL @@ -2394,7 +3063,7 @@ force_cctx () PROTOTYPE: CODE: - SvSTATE_current->cctx->idle_sp = 0; + cctx_current->idle_sp = 0; void swap_defsv (Coro::State self) @@ -2412,18 +3081,26 @@ SV *tmp = *src; *src = *dst; *dst = tmp; } + MODULE = Coro::State PACKAGE = Coro BOOT: { int i; - av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE); - sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE); - sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE); - - coro_current = coro_get_sv (aTHX_ "Coro::current", FALSE); - SvREADONLY_on (coro_current); + sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE); + sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE); + cv_coro_run = get_cv ( "Coro::_terminate", GV_ADD); + cv_coro_terminate = get_cv ( "Coro::terminate" , GV_ADD); + coro_current = coro_get_sv (aTHX_ "Coro::current" , FALSE); SvREADONLY_on (coro_current); + av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE); + av_destroy = coro_get_av (aTHX_ "Coro::destroy" , TRUE); + sv_manager = coro_get_sv (aTHX_ "Coro::manager" , TRUE); + + sv_async_pool_idle = newSVpv ("[async pool idle]", 0); SvREADONLY_on (sv_async_pool_idle); + sv_Coro = newSVpv ("Coro", 0); SvREADONLY_on (sv_Coro); + cv_pool_handler = get_cv ("Coro::pool_handler", GV_ADD); SvREADONLY_on (cv_pool_handler); + cv_coro_state_new = get_cv ("Coro::State::new", 0); SvREADONLY_on (cv_coro_state_new); coro_stash = gv_stashpv ("Coro", TRUE); @@ -2441,6 +3118,7 @@ SV *sv = coro_get_sv (aTHX_ "Coro::API", TRUE); coroapi.schedule = api_schedule; + coroapi.schedule_to = api_schedule_to; coroapi.cede = api_cede; coroapi.cede_notself = api_cede_notself; coroapi.ready = api_ready; @@ -2448,26 +3126,47 @@ coroapi.nready = coro_nready; coroapi.current = coro_current; - GCoroAPI = &coroapi; + /*GCoroAPI = &coroapi;*/ sv_setiv (sv, (IV)&coroapi); SvREADONLY_on (sv); } } void +terminate (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_terminate); + +void schedule (...) CODE: - api_execute_slf (aTHX_ cv, slf_init_schedule, &ST (0), 0); + CORO_EXECUTE_SLF_XS (slf_init_schedule); + +void +schedule_to (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_schedule_to); + +void +cede_to (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_cede_to); void cede (...) CODE: - api_execute_slf (aTHX_ cv, slf_init_cede, &ST (0), 0); + CORO_EXECUTE_SLF_XS (slf_init_cede); void cede_notself (...) CODE: - api_execute_slf (aTHX_ cv, slf_init_cede_notself, &ST (0), 0); + CORO_EXECUTE_SLF_XS (slf_init_cede_notself); + +void +_cancel (Coro::State self) + CODE: + coro_state_destroy (aTHX_ self); + coro_call_on_destroy (aTHX_ self); void _set_current (SV *current) @@ -2522,158 +3221,68 @@ OUTPUT: RETVAL -# for async_pool speedup void -_pool_1 (SV *cb) +_pool_handler (...) CODE: -{ - HV *hv = (HV *)SvRV (coro_current); - struct coro *coro = SvSTATE_hv ((SV *)hv); - AV *defav = GvAV (PL_defgv); - SV *invoke = hv_delete (hv, "_invoke", sizeof ("_invoke") - 1, 0); - AV *invoke_av; - int i, len; - - if (!invoke) - { - SV *old = PL_diehook; - PL_diehook = 0; - SvREFCNT_dec (old); - croak ("\3async_pool terminate\2\n"); - } - - SvREFCNT_dec (coro->saved_deffh); - coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv); - - hv_store (hv, "desc", sizeof ("desc") - 1, - newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0); - - invoke_av = (AV *)SvRV (invoke); - len = av_len (invoke_av); - - sv_setsv (cb, AvARRAY (invoke_av)[0]); - - if (len > 0) - { - av_fill (defav, len - 1); - for (i = 0; i < len; ++i) - av_store (defav, i, SvREFCNT_inc_NN (AvARRAY (invoke_av)[i + 1])); - } -} + CORO_EXECUTE_SLF_XS (slf_init_pool_handler); void -_pool_2 (SV *cb) - CODE: -{ - struct coro *coro = SvSTATE_current; - - sv_setsv (cb, &PL_sv_undef); - - SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh; - coro->saved_deffh = 0; - - if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss) - || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size)) - { - SV *old = PL_diehook; - PL_diehook = 0; - SvREFCNT_dec (old); - croak ("\3async_pool terminate\2\n"); - } - - av_clear (GvAV (PL_defgv)); - hv_store ((HV *)SvRV (coro_current), "desc", sizeof ("desc") - 1, - newSVpvn ("[async_pool idle]", sizeof ("[async_pool idle]") - 1), 0); - - coro->prio = 0; - - if (coro->cctx && (coro->cctx->flags & CC_TRACE)) - api_trace (aTHX_ coro_current, 0); - - av_push (av_async_pool, newSVsv (coro_current)); -} - - -MODULE = Coro::State PACKAGE = Coro::AIO - -void -_get_state (SV *self) - PROTOTYPE: $ - PPCODE: +async_pool (SV *cv, ...) + PROTOTYPE: &@ + PPCODE: { - AV *defav = GvAV (PL_defgv); + HV *hv = (HV *)av_pop (av_async_pool); AV *av = newAV (); + SV *cb = ST (0); int i; - SV *data_sv = newSV (sizeof (struct io_state)); - struct io_state *data = (struct io_state *)SvPVX (data_sv); - SvCUR_set (data_sv, sizeof (struct io_state)); - SvPOK_only (data_sv); - - data->errorno = errno; - data->laststype = PL_laststype; - data->laststatval = PL_laststatval; - data->statcache = PL_statcache; - av_extend (av, AvFILLp (defav) + 1 + 1); + av_extend (av, items - 2); + for (i = 1; i < items; ++i) + av_push (av, SvREFCNT_inc_NN (ST (i))); - for (i = 0; i <= AvFILLp (defav); ++i) - av_push (av, SvREFCNT_inc_NN (AvARRAY (defav)[i])); + if ((SV *)hv == &PL_sv_undef) + { + PUSHMARK (SP); + EXTEND (SP, 2); + PUSHs (sv_Coro); + PUSHs ((SV *)cv_pool_handler); + PUTBACK; + call_sv ((SV *)cv_coro_state_new, G_SCALAR); + SPAGAIN; - av_push (av, data_sv); + hv = (HV *)SvREFCNT_inc_NN (SvRV (POPs)); + } - XPUSHs (sv_2mortal (newRV_noinc ((SV *)av))); + { + struct coro *coro = SvSTATE_hv (hv); - api_ready (aTHX_ self); -} + assert (!coro->invoke_cb); + assert (!coro->invoke_av); + coro->invoke_cb = SvREFCNT_inc (cb); + coro->invoke_av = av; + } -void -_set_state (SV *state) - PROTOTYPE: $ - PPCODE: -{ - AV *av = (AV *)SvRV (state); - struct io_state *data = (struct io_state *)SvPVX (AvARRAY (av)[AvFILLp (av)]); - int i; + api_ready (aTHX_ (SV *)hv); - errno = data->errorno; - PL_laststype = data->laststype; - PL_laststatval = data->laststatval; - PL_statcache = data->statcache; - - EXTEND (SP, AvFILLp (av)); - for (i = 0; i < AvFILLp (av); ++i) - PUSHs (sv_2mortal (SvREFCNT_inc_NN (AvARRAY (av)[i]))); + if (GIMME_V != G_VOID) + XPUSHs (sv_2mortal (newRV_noinc ((SV *)hv))); + else + SvREFCNT_dec (hv); } - -MODULE = Coro::State PACKAGE = Coro::AnyEvent - -BOOT: - sv_activity = coro_get_sv (aTHX_ "Coro::AnyEvent::ACTIVITY", TRUE); - -void -_schedule (...) +SV * +rouse_cb () + PROTOTYPE: CODE: -{ - static int incede; - - api_cede_notself (aTHX); - - ++incede; - while (coro_nready >= incede && api_cede (aTHX)) - ; - - sv_setsv (sv_activity, &PL_sv_undef); - if (coro_nready >= incede) - { - PUSHMARK (SP); - PUTBACK; - call_pv ("Coro::AnyEvent::_activity", G_DISCARD | G_EVAL); - SPAGAIN; - } + RETVAL = coro_new_rouse_cb (aTHX); + OUTPUT: + RETVAL - --incede; -} +void +rouse_wait (...) + PROTOTYPE: ;$ + PPCODE: + CORO_EXECUTE_SLF_XS (slf_init_rouse_wait); MODULE = Coro::State PACKAGE = PerlIO::cede @@ -2681,17 +3290,24 @@ BOOT: PerlIO_define_layer (aTHX_ &PerlIO_cede); + MODULE = Coro::State PACKAGE = Coro::Semaphore SV * -new (SV *klass, SV *count_ = 0) +new (SV *klass, SV *count = 0) CODE: -{ - /* a semaphore contains a counter IV in $sem->[0] and any waiters after that */ - AV *av = newAV (); - av_push (av, newSViv (count_ && SvOK (count_) ? SvIV (count_) : 1)); - RETVAL = sv_bless (newRV_noinc ((SV *)av), GvSTASH (CvGV (cv))); -} + RETVAL = sv_bless ( + coro_waitarray_new (aTHX_ count && SvOK (count) ? SvIV (count) : 1), + GvSTASH (CvGV (cv)) + ); + OUTPUT: + RETVAL + +# helper for Coro::Channel +SV * +_alloc (int count) + CODE: + RETVAL = coro_waitarray_new (aTHX_ count); OUTPUT: RETVAL @@ -2710,9 +3326,14 @@ coro_semaphore_adjust (aTHX_ (AV *)SvRV (self), ix ? adjust : 1); void -down (SV *self) +down (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_semaphore_down); + +void +wait (...) CODE: - api_execute_slf (aTHX_ cv, slf_init_semaphore_down, &ST (0), 1); + CORO_EXECUTE_SLF_XS (slf_init_semaphore_wait); void try (SV *self) @@ -2734,18 +3355,106 @@ void waiters (SV *self) - CODE: + PPCODE: { AV *av = (AV *)SvRV (self); + int wcount = AvFILLp (av) + 1 - 1; if (GIMME_V == G_SCALAR) - XPUSHs (sv_2mortal (newSVsv (AvARRAY (av)[0]))); + XPUSHs (sv_2mortal (newSViv (wcount))); else { int i; - EXTEND (SP, AvFILLp (av) + 1 - 1); - for (i = 1; i <= AvFILLp (av); ++i) - PUSHs (newSVsv (AvARRAY (av)[i])); + EXTEND (SP, wcount); + for (i = 1; i <= wcount; ++i) + PUSHs (sv_2mortal (newRV_inc (AvARRAY (av)[i]))); + } +} + +MODULE = Coro::State PACKAGE = Coro::Signal + +SV * +new (SV *klass) + CODE: + RETVAL = sv_bless ( + coro_waitarray_new (aTHX_ 0), + GvSTASH (CvGV (cv)) + ); + OUTPUT: + RETVAL + +void +wait (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_signal_wait); + +void +broadcast (SV *self) + CODE: +{ + AV *av = (AV *)SvRV (self); + coro_signal_wake (aTHX_ av, AvFILLp (av)); +} + +void +send (SV *self) + CODE: +{ + AV *av = (AV *)SvRV (self); + + if (AvFILLp (av)) + coro_signal_wake (aTHX_ av, 1); + else + SvIVX (AvARRAY (av)[0]) = 1; /* remember the signal */ +} + +IV +awaited (SV *self) + CODE: + RETVAL = AvFILLp ((AV *)SvRV (self)) + 1 - 1; + OUTPUT: + RETVAL + + +MODULE = Coro::State PACKAGE = Coro::AnyEvent + +BOOT: + sv_activity = coro_get_sv (aTHX_ "Coro::AnyEvent::ACTIVITY", TRUE); + +void +_schedule (...) + CODE: +{ + static int incede; + + api_cede_notself (aTHX); + + ++incede; + while (coro_nready >= incede && api_cede (aTHX)) + ; + + sv_setsv (sv_activity, &PL_sv_undef); + if (coro_nready >= incede) + { + PUSHMARK (SP); + PUTBACK; + call_pv ("Coro::AnyEvent::_activity", G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); } + + --incede; +} + + +MODULE = Coro::State PACKAGE = Coro::AIO + +void +_register (char *target, char *proto, SV *req) + CODE: +{ + CV *req_cv = coro_sv_2cv (aTHX_ req); + /* newXSproto doesn't return the CV on 5.8 */ + CV *slf_cv = newXS (target, coro_aio_req_xs, __FILE__); + sv_setpv ((SV *)slf_cv, proto); + sv_magicext ((SV *)slf_cv, (SV *)req_cv, CORO_MAGIC_type_aio, 0, 0, 0); }