source: libcfa/src/concurrency/coroutine.hfa @ c34bb1f

Last change on this file since c34bb1f was c34bb1f, checked in by caparsons <caparson@…>, 11 months ago

fixed nonlocal exception edge case for program main and added poll() routine with no args that polls the currrent active coroutine

  • Property mode set to 100644
File size: 8.3 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// coroutine --
8//
9// Author           : Thierry Delisle
10// Created On       : Mon Nov 28 12:27:26 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Feb  2 11:31:42 2023
13// Update Count     : 13
14//
15
16#pragma once
17
18#include <assert.h>
19#include "invoke.h"
20#include "../exception.hfa"
21
22//-----------------------------------------------------------------------------
23// Type used to store and queue nonlocal exceptions on coroutines
24struct nonlocal_exception {
25    exception_t * the_exception;
26    nonlocal_exception * next;
27};
28static inline void ?{} ( nonlocal_exception & this, exception_t * ex ) with(this) {
29    the_exception = ex;
30    next = 0p;
31}
32
33static inline nonlocal_exception *& get_next( nonlocal_exception & this ) __attribute__((const)) {
34    return this.next;
35}
36
37//-----------------------------------------------------------------------------
38// Exception thrown from resume when a coroutine stack is cancelled.
39forall(coroutine_t &)
40exception CoroutineCancelled {
41        coroutine_t * the_coroutine;
42        exception_t * the_exception;
43};
44
45forall(T &)
46void copy(CoroutineCancelled(T) * dst, CoroutineCancelled(T) * src);
47
48forall(T &)
49const char * msg(CoroutineCancelled(T) *);
50
51//-----------------------------------------------------------------------------
52// Coroutine trait
53// Anything that implements this trait can be resumed.
54// Anything that is resumed is a coroutine.
55forall( T & | IS_RESUMPTION_EXCEPTION(CoroutineCancelled(T)) )
56trait is_coroutine {
57        void main(T & this);
58        coroutine$ * get_coroutine(T & this);
59};
60
61#define DECL_COROUTINE(X) static inline coroutine$* get_coroutine(X& this) { return &this.__cor; } void main(X& this)
62
63//-----------------------------------------------------------------------------
64// Ctors and dtors
65// void ?{}( coStack_t & this );
66// void ^?{}( coStack_t & this );
67
68void  ?{}( coroutine$ & this, const char name[], void * storage, size_t storageSize );
69void ^?{}( coroutine$ & this );
70
71static inline void ?{}( coroutine$ & this)                                       { this{ "Anonymous Coroutine", 0p, 0 }; }
72static inline void ?{}( coroutine$ & this, size_t stackSize)                     { this{ "Anonymous Coroutine", 0p, stackSize }; }
73static inline void ?{}( coroutine$ & this, void * storage, size_t storageSize )  { this{ "Anonymous Coroutine", storage, storageSize }; }
74static inline void ?{}( coroutine$ & this, const char name[])                    { this{ name, 0p, 0 }; }
75static inline void ?{}( coroutine$ & this, const char name[], size_t stackSize ) { this{ name, 0p, stackSize }; }
76
77//-----------------------------------------------------------------------------
78// Public coroutine API
79forall(T & | is_coroutine(T) | { EHM_DEFAULT_VTABLE(CoroutineCancelled(T)); })
80void prime(T & cor);
81
82static inline struct coroutine$ * active_coroutine() { return active_thread()->curr_cor; }
83
84//-----------------------------------------------------------------------------
85// PRIVATE exposed because of inline
86
87// Start coroutine routines
88extern "C" {
89        void __cfactx_invoke_coroutine(void (*main)(void *), void * this);
90
91        forall(T &)
92        void __cfactx_start(void (*main)(T &), struct coroutine$ * cor, T & this, void (*invoke)(void (*main)(void *), void *));
93
94        extern void __cfactx_coroutine_unwind(struct _Unwind_Exception * storage, struct coroutine$ *) __attribute__ ((__noreturn__));
95
96        extern void __cfactx_switch( struct __stack_context_t * from, struct __stack_context_t * to ) asm ("__cfactx_switch");
97}
98
99// Private wrappers for context switch and stack creation
100// Wrapper for co
101static inline void $ctx_switch( coroutine$ * src, coroutine$ * dst ) __attribute__((nonnull (1, 2))) {
102        // set state of current coroutine to inactive
103        src->state = src->state == Halted ? Halted : Blocked;
104
105        // get the active thread once
106        thread$ * athrd = active_thread();
107
108        // Mark the coroutine
109        /* paranoid */ verify( !athrd->corctx_flag );
110        athrd->corctx_flag = true;
111
112        // set new coroutine that task is executing
113        athrd->curr_cor = dst;
114
115        // context switch to specified coroutine
116        /* paranoid */ verify( dst->context.SP );
117        __cfactx_switch( &src->context, &dst->context );
118        // when __cfactx_switch returns we are back in the src coroutine
119
120        /* paranoid */ verify( athrd->corctx_flag );
121        athrd->corctx_flag = false;
122
123        // set state of new coroutine to active
124        src->state = Active;
125
126        if( unlikely(src->cancellation != 0p) ) {
127                __cfactx_coroutine_unwind(src->cancellation, src);
128        }
129}
130
131extern void __stack_prepare( __stack_info_t * this, size_t size /* ignored if storage already allocated */);
132
133// Suspend implementation inlined for performance
134extern "C" {
135        static inline void __cfactx_suspend(void) {
136                // optimization : read TLS once and reuse it
137                // Safety note: this is preemption safe since if
138                // preemption occurs after this line, the pointer
139                // will also migrate which means this value will
140                // stay in syn with the TLS
141                coroutine$ * src = active_coroutine();
142
143                assertf( src->last != 0,
144                        "Attempt to suspend coroutine \"%.256s\" (%p) that has never been resumed.\n"
145                        "Possible cause is a suspend executed in a member called by a coroutine user rather than by the coroutine main.",
146                        src->name, src );
147                assertf( src->last->state != Halted,
148                        "Attempt by coroutine \"%.256s\" (%p) to suspend back to terminated coroutine \"%.256s\" (%p).\n"
149                        "Possible cause is terminated coroutine's main routine has already returned.",
150                        src->name, src, src->last->name, src->last );
151
152                $ctx_switch( src, src->last );
153        }
154}
155
156forall(T & | is_coroutine(T))
157void __cfaehm_cancelled_coroutine(
158        T & cor, coroutine$ * desc, EHM_DEFAULT_VTABLE(CoroutineCancelled(T)) );
159
160// Resume implementation inlined for performance
161forall(T & | is_coroutine(T) | { EHM_DEFAULT_VTABLE(CoroutineCancelled(T)); })
162static inline T & resume(T & cor) {
163        // optimization : read TLS once and reuse it
164        // Safety note: this is preemption safe since if
165        // preemption occurs after this line, the pointer
166        // will also migrate which means this value will
167        // stay in syn with the TLS
168        coroutine$ * src = active_coroutine();
169        coroutine$ * dst = get_coroutine(cor);
170
171        if( unlikely(dst->context.SP == 0p) ) {
172                __stack_prepare(&dst->stack, DEFAULT_STACK_SIZE);
173                __cfactx_start(main, dst, cor, __cfactx_invoke_coroutine);
174        }
175
176        // not resuming self ?
177        if ( src != dst ) {
178                assertf( dst->state != Halted ,
179                        "Attempt by coroutine %.256s (%p) to resume terminated coroutine %.256s (%p).\n"
180                        "Possible cause is terminated coroutine's main routine has already returned.",
181                        src->name, src, dst->name, dst );
182
183                // set last resumer
184                dst->last = src;
185                dst->starter = dst->starter ? dst->starter : src;
186        }
187
188        // always done for performance testing
189        $ctx_switch( src, dst );
190        if ( unlikely(dst->cancellation) ) {
191                __cfaehm_cancelled_coroutine( cor, dst, _default_vtable );
192        }
193
194        return cor;
195}
196
197static inline void resume( coroutine$ * dst ) __attribute__((nonnull (1))) {
198        // optimization : read TLS once and reuse it
199        // Safety note: this is preemption safe since if
200        // preemption occurs after this line, the pointer
201        // will also migrate which means this value will
202        // stay in syn with the TLS
203        coroutine$ * src = active_coroutine();
204
205        // not resuming self ?
206        if ( src != dst ) {
207                assertf( dst->state != Halted ,
208                        "Attempt by coroutine %.256s (%p) to resume terminated coroutine %.256s (%p).\n"
209                        "Possible cause is terminated coroutine's main routine has already returned.",
210                        src->name, src, dst->name, dst );
211
212                // set last resumer
213                dst->last = src;
214        }
215
216        // always done for performance testing
217        $ctx_switch( src, dst );
218}
219
220// non local ehm and coroutine utility routines
221bool poll( coroutine$ * cor );
222bool poll();
223
224forall(T & | is_coroutine(T)) {
225    void enable_ehm( T & cor );
226    void disable_ehm( T & cor );
227    bool poll( T & cor );
228    bool checked_poll( T & cor );
229    coroutine$ * resumer( T & cor );
230}
231
232// trait for exceptions able to be resumed at another coroutine
233forall(exceptT &, T & | is_coroutine(T))
234trait ehm_resume_at { void $throwResume(exceptT &); };
235
236// general resumeAt
237forall(exceptT &, T & | ehm_resume_at( exceptT, T ))
238void resumeAt( T & receiver, exceptT & ex );
239
240// resumeAt for underlying coroutine$ type
241forall(exceptT & | { void $throwResume(exceptT &); })
242void resumeAt( coroutine$ * receiver, exceptT & ex );
243
244// Local Variables: //
245// mode: c //
246// tab-width: 4 //
247// End: //
Note: See TracBrowser for help on using the repository browser.