source: libcfa/src/concurrency/channel.hfa@ 1b0184b

Last change on this file since 1b0184b was ca995e3, checked in by caparsons <caparson@…>, 2 years ago

added missing ARM fence on the signallee side of channel handoff

  • Property mode set to 100644
File size: 21.0 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2021 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// channel.hfa -- LIBCFATHREAD
8// Runtime locks that used with the runtime thread system.
9//
10// Author : Colby Alexander Parsons
11// Created On : Thu Jan 21 19:46:50 2022
12// Last Modified By :
13// Last Modified On :
14// Update Count :
15//
16
17#pragma once
18
19#include <locks.hfa>
20#include <list.hfa>
21#include "select.hfa"
22
23// returns true if woken due to shutdown
24// blocks thread on list and releases passed lock
25static inline bool block( dlist( select_node ) & queue, void * elem_ptr, go_mutex & lock ) {
26 select_node sn{ active_thread(), elem_ptr };
27 insert_last( queue, sn );
28 unlock( lock );
29 park();
30 __atomic_thread_fence( __ATOMIC_SEQ_CST );
31 return sn.extra == 0p;
32}
33
34// Waituntil support (un)register_select helper routine
35// Sets select node avail if not special OR case and then unlocks
36static inline void __set_avail_then_unlock( select_node & node, go_mutex & mutex_lock ) {
37 if ( node.park_counter ) __make_select_node_available( node );
38 unlock( mutex_lock );
39}
40
41// void * used for some fields since exceptions don't work with parametric polymorphism currently
42exception channel_closed {
43 // on failed insert elem is a ptr to the element attempting to be inserted
44 // on failed remove elem ptr is 0p
45 // on resumption of a failed insert this elem will be inserted
46 // so a user may modify it in the resumption handler
47 void * elem;
48
49 // pointer to chan that is closed
50 void * closed_chan;
51};
52vtable(channel_closed) channel_closed_vt;
53
54static inline bool is_insert( channel_closed & e ) { return e.elem != 0p; }
55static inline bool is_remove( channel_closed & e ) { return e.elem == 0p; }
56
57// #define CHAN_STATS // define this to get channel stats printed in dtor
58
59forall( T ) {
60
61struct __attribute__((aligned(128))) channel {
62 size_t size, front, back, count;
63 T * buffer;
64 dlist( select_node ) prods, cons; // lists of blocked threads
65 go_mutex mutex_lock; // MX lock
66 bool closed; // indicates channel close/open
67 #ifdef CHAN_STATS
68 size_t p_blocks, p_ops, c_blocks, c_ops; // counts total ops and ops resulting in a blocked thd
69 #endif
70};
71static inline void ?{}( channel(T) & this, channel(T) this2 ) = void;
72static inline void ?=?( channel(T) & this, channel(T) this2 ) = void;
73
74static inline void ?{}( channel(T) &c, size_t _size ) with(c) {
75 size = _size;
76 front = back = count = 0;
77 if ( size != 0 ) buffer = aalloc( size );
78 prods{};
79 cons{};
80 mutex_lock{};
81 closed = false;
82 #ifdef CHAN_STATS
83 p_blocks = 0;
84 p_ops = 0;
85 c_blocks = 0;
86 c_ops = 0;
87 #endif
88}
89
90static inline void ?{}( channel(T) &c ){ ((channel(T) &)c){ 0 }; }
91static inline void ^?{}( channel(T) &c ) with(c) {
92 #ifdef CHAN_STATS
93 printf("Channel %p Blocks: %lu,\t\tOperations: %lu,\t%.2f%% of ops blocked\n", &c, p_blocks + c_blocks, p_ops + c_ops, ((double)p_blocks + c_blocks)/(p_ops + c_ops) * 100);
94 printf("Channel %p Consumer Blocks: %lu,\tConsumer Ops: %lu,\t%.2f%% of Consumer ops blocked\n", &c, p_blocks, p_ops, ((double)p_blocks)/p_ops * 100);
95 printf("Channel %p Producer Blocks: %lu,\tProducer Ops: %lu,\t%.2f%% of Producer ops blocked\n", &c, c_blocks, c_ops, ((double)c_blocks)/c_ops * 100);
96 #endif
97 verifyf( __handle_waituntil_OR( cons ) || __handle_waituntil_OR( prods ) || cons`isEmpty && prods`isEmpty,
98 "Attempted to delete channel with waiting threads (Deadlock).\n" );
99 if ( size != 0 ) delete( buffer );
100}
101static inline size_t get_count( channel(T) & chan ) with(chan) { return __atomic_load_n( &count, __ATOMIC_RELAXED ); }
102static inline size_t get_size( channel(T) & chan ) with(chan) { return __atomic_load_n( &size, __ATOMIC_RELAXED ); }
103static inline bool has_waiters( channel(T) & chan ) with(chan) { return !cons`isEmpty || !prods`isEmpty; }
104static inline bool has_waiting_consumers( channel(T) & chan ) with(chan) { return !cons`isEmpty; }
105static inline bool has_waiting_producers( channel(T) & chan ) with(chan) { return !prods`isEmpty; }
106
107// closes the channel and notifies all blocked threads
108static inline void close( channel(T) & chan ) with(chan) {
109 lock( mutex_lock );
110 closed = true;
111
112 // flush waiting consumers and producers
113 while ( has_waiting_consumers( chan ) ) {
114 if( !__handle_waituntil_OR( cons ) ) // ensure we only signal special OR case threads when they win the race
115 break; // if __handle_waituntil_OR returns false cons is empty so break
116 cons`first.extra = 0p;
117 wake_one( cons );
118 }
119 while ( has_waiting_producers( chan ) ) {
120 if( !__handle_waituntil_OR( prods ) ) // ensure we only signal special OR case threads when they win the race
121 break; // if __handle_waituntil_OR returns false prods is empty so break
122 prods`first.extra = 0p;
123 wake_one( prods );
124 }
125 unlock(mutex_lock);
126}
127
128static inline void is_closed( channel(T) & chan ) with(chan) { return closed; }
129
130// used to hand an element to a blocked consumer and signal it
131static inline void __cons_handoff( channel(T) & chan, T & elem ) with(chan) {
132 memcpy( cons`first.extra, (void *)&elem, sizeof(T) ); // do waiting consumer work
133 __atomic_thread_fence( __ATOMIC_SEQ_CST );
134 wake_one( cons );
135}
136
137// used to hand an element to a blocked producer and signal it
138static inline void __prods_handoff( channel(T) & chan, T & retval ) with(chan) {
139 memcpy( (void *)&retval, prods`first.extra, sizeof(T) );
140 __atomic_thread_fence( __ATOMIC_SEQ_CST );
141 wake_one( prods );
142}
143
144static inline void flush( channel(T) & chan, T elem ) with(chan) {
145 lock( mutex_lock );
146 while ( count == 0 && !cons`isEmpty ) {
147 __cons_handoff( chan, elem );
148 }
149 unlock( mutex_lock );
150}
151
152// handles buffer insert
153static inline void __buf_insert( channel(T) & chan, T & elem ) with(chan) {
154 memcpy( (void *)&buffer[back], (void *)&elem, sizeof(T) );
155 count += 1;
156 back++;
157 if ( back == size ) back = 0;
158}
159
160// needed to avoid an extra copy in closed case
161static inline bool __internal_try_insert( channel(T) & chan, T & elem ) with(chan) {
162 lock( mutex_lock );
163 #ifdef CHAN_STATS
164 p_ops++;
165 #endif
166
167 ConsEmpty: if ( !cons`isEmpty ) {
168 if ( !__handle_waituntil_OR( cons ) ) break ConsEmpty;
169 __cons_handoff( chan, elem );
170 unlock( mutex_lock );
171 return true;
172 }
173
174 if ( count == size ) { unlock( mutex_lock ); return false; }
175
176 __buf_insert( chan, elem );
177 unlock( mutex_lock );
178 return true;
179}
180
181// attempts a nonblocking insert
182// returns true if insert was successful, false otherwise
183static inline bool try_insert( channel(T) & chan, T elem ) { return __internal_try_insert( chan, elem ); }
184
185// handles closed case of insert routine
186static inline void __closed_insert( channel(T) & chan, T & elem ) with(chan) {
187 channel_closed except{ &channel_closed_vt, &elem, &chan };
188 throwResume except; // throw closed resumption
189 if ( !__internal_try_insert( chan, elem ) ) throw except; // if try to insert fails (would block), throw termination
190}
191
192static inline void insert( channel(T) & chan, T elem ) with(chan) {
193 // check for close before acquire mx
194 if ( unlikely(closed) ) {
195 __closed_insert( chan, elem );
196 return;
197 }
198
199 lock( mutex_lock );
200
201 #ifdef CHAN_STATS
202 if ( !closed ) p_ops++;
203 #endif
204
205 // if closed handle
206 if ( unlikely(closed) ) {
207 unlock( mutex_lock );
208 __closed_insert( chan, elem );
209 return;
210 }
211
212 // buffer count must be zero if cons are blocked (also handles zero-size case)
213 ConsEmpty: if ( !cons`isEmpty ) {
214 if ( !__handle_waituntil_OR( cons ) ) break ConsEmpty;
215 __cons_handoff( chan, elem );
216 unlock( mutex_lock );
217 return;
218 }
219
220 // wait if buffer is full, work will be completed by someone else
221 if ( count == size ) {
222 #ifdef CHAN_STATS
223 p_blocks++;
224 #endif
225
226 // check for if woken due to close
227 if ( unlikely( block( prods, &elem, mutex_lock ) ) )
228 __closed_insert( chan, elem );
229 return;
230 } // if
231
232 __buf_insert( chan, elem );
233 unlock( mutex_lock );
234}
235
236// does the buffer remove and potentially does waiting producer work
237static inline void __do_remove( channel(T) & chan, T & retval ) with(chan) {
238 memcpy( (void *)&retval, (void *)&buffer[front], sizeof(T) );
239 count -= 1;
240 front = (front + 1) % size;
241 if (count == size - 1 && !prods`isEmpty ) {
242 if ( !__handle_waituntil_OR( prods ) ) return;
243 __buf_insert( chan, *(T *)prods`first.extra ); // do waiting producer work
244 wake_one( prods );
245 }
246}
247
248// needed to avoid an extra copy in closed case and single return val case
249static inline bool __internal_try_remove( channel(T) & chan, T & retval ) with(chan) {
250 lock( mutex_lock );
251 #ifdef CHAN_STATS
252 c_ops++;
253 #endif
254
255 ZeroSize: if ( size == 0 && !prods`isEmpty ) {
256 if ( !__handle_waituntil_OR( prods ) ) break ZeroSize;
257 __prods_handoff( chan, retval );
258 unlock( mutex_lock );
259 return true;
260 }
261
262 if ( count == 0 ) { unlock( mutex_lock ); return false; }
263
264 __do_remove( chan, retval );
265 unlock( mutex_lock );
266 return true;
267}
268
269// attempts a nonblocking remove
270// returns [T, true] if insert was successful
271// returns [T, false] if insert was successful (T uninit)
272static inline [T, bool] try_remove( channel(T) & chan ) {
273 T retval;
274 bool success = __internal_try_remove( chan, retval );
275 return [ retval, success ];
276}
277
278static inline T try_remove( channel(T) & chan ) {
279 T retval;
280 __internal_try_remove( chan, retval );
281 return retval;
282}
283
284// handles closed case of insert routine
285static inline void __closed_remove( channel(T) & chan, T & retval ) with(chan) {
286 channel_closed except{ &channel_closed_vt, 0p, &chan };
287 throwResume except; // throw resumption
288 if ( !__internal_try_remove( chan, retval ) ) throw except; // if try to remove fails (would block), throw termination
289}
290
291static inline T remove( channel(T) & chan ) with(chan) {
292 T retval;
293 if ( unlikely(closed) ) {
294 __closed_remove( chan, retval );
295 return retval;
296 }
297 lock( mutex_lock );
298
299 #ifdef CHAN_STATS
300 if ( !closed ) c_ops++;
301 #endif
302
303 if ( unlikely(closed) ) {
304 unlock( mutex_lock );
305 __closed_remove( chan, retval );
306 return retval;
307 }
308
309 // have to check for the zero size channel case
310 ZeroSize: if ( size == 0 && !prods`isEmpty ) {
311 if ( !__handle_waituntil_OR( prods ) ) break ZeroSize;
312 __prods_handoff( chan, retval );
313 unlock( mutex_lock );
314 return retval;
315 }
316
317 // wait if buffer is empty, work will be completed by someone else
318 if ( count == 0 ) {
319 #ifdef CHAN_STATS
320 c_blocks++;
321 #endif
322 // check for if woken due to close
323 if ( unlikely( block( cons, &retval, mutex_lock ) ) )
324 __closed_remove( chan, retval );
325 return retval;
326 }
327
328 // Remove from buffer
329 __do_remove( chan, retval );
330 unlock( mutex_lock );
331 return retval;
332}
333static inline void remove( channel(T) & chan ) { T elem = (T)remove( chan ); }
334
335
336///////////////////////////////////////////////////////////////////////////////////////////
337// The following is Go-style operator support for channels
338///////////////////////////////////////////////////////////////////////////////////////////
339
340static inline void ?<<?( channel(T) & chan, T elem ) { insert( chan, elem ); }
341static inline void ?<<?( T & ret, channel(T) & chan ) { ret = remove( chan ); }
342
343///////////////////////////////////////////////////////////////////////////////////////////
344// The following is support for waituntil (select) statements
345///////////////////////////////////////////////////////////////////////////////////////////
346static inline bool unregister_chan( channel(T) & chan, select_node & node ) with(chan) {
347 if ( !node`isListed && !node.park_counter ) return false; // handle special OR case
348 lock( mutex_lock );
349 if ( node`isListed ) { // op wasn't performed
350 remove( node );
351 unlock( mutex_lock );
352 return false;
353 }
354 unlock( mutex_lock );
355
356 // only return true when not special OR case and status is SAT
357 return !node.park_counter ? false : *node.clause_status == __SELECT_SAT;
358}
359
360// special case of __handle_waituntil_OR, that does some work to avoid starvation/deadlock case
361static inline bool __handle_pending( dlist( select_node ) & queue, select_node & mine ) {
362 while ( !queue`isEmpty ) {
363 // if node not a special OR case or if we win the special OR case race break
364 if ( !queue`first.clause_status || queue`first.park_counter || __pending_set_other( queue`first, mine, ((unsigned long int)(&(queue`first))) ) )
365 return true;
366
367 // our node lost the race when toggling in __pending_set_other
368 if ( *mine.clause_status != __SELECT_PENDING )
369 return false;
370
371 // otherwise we lost the special OR race so discard node
372 try_pop_front( queue );
373 }
374 return false;
375}
376
377// type used by select statement to capture a chan read as the selected operation
378struct chan_read {
379 T * ret;
380 channel(T) * chan;
381};
382__CFA_SELECT_GET_TYPE( chan_read(T) );
383
384static inline void ?{}( chan_read(T) & cr, channel(T) * chan, T * ret ) {
385 cr.chan = chan;
386 cr.ret = ret;
387}
388static inline chan_read(T) ?<<?( T & ret, channel(T) & chan ) { chan_read(T) cr{ &chan, &ret }; return cr; }
389
390static inline void __handle_select_closed_read( chan_read(T) & this, select_node & node ) with(*this.chan, this) {
391 __closed_remove( *chan, *ret );
392 // if we get here then the insert succeeded
393 __make_select_node_available( node );
394}
395
396static inline bool register_select( chan_read(T) & this, select_node & node ) with(*this.chan, this) {
397 lock( mutex_lock );
398 node.extra = ret; // set .extra so that if it == 0p later in on_selected it is due to channel close
399
400 #ifdef CHAN_STATS
401 if ( !closed ) c_ops++;
402 #endif
403
404 if ( !node.park_counter ) {
405 // are we special case OR and front of cons is also special case OR
406 if ( !unlikely(closed) && !prods`isEmpty && prods`first.clause_status && !prods`first.park_counter ) {
407 if ( !__make_select_node_pending( node ) ) {
408 unlock( mutex_lock );
409 return false;
410 }
411
412 if ( __handle_pending( prods, node ) ) {
413 __prods_handoff( *chan, *ret );
414 __make_select_node_sat( node ); // need to to mark SAT now that we know operation is done or else threads could get stuck in __mark_select_node
415 unlock( mutex_lock );
416 return true;
417 }
418 if ( *node.clause_status == __SELECT_PENDING )
419 __make_select_node_unsat( node );
420 }
421 // check if we can complete operation. If so race to establish winner in special OR case
422 if ( count != 0 || !prods`isEmpty || unlikely(closed) ) {
423 if ( !__make_select_node_available( node ) ) { // we didn't win the race so give up on registering
424 unlock( mutex_lock );
425 return false;
426 }
427 }
428 }
429
430 if ( unlikely(closed) ) {
431 unlock( mutex_lock );
432 __handle_select_closed_read( this, node );
433 return true;
434 }
435
436 // have to check for the zero size channel case
437 ZeroSize: if ( size == 0 && !prods`isEmpty ) {
438 if ( !__handle_waituntil_OR( prods ) ) break ZeroSize;
439 __prods_handoff( *chan, *ret );
440 __set_avail_then_unlock( node, mutex_lock );
441 return true;
442 }
443
444 // wait if buffer is empty, work will be completed by someone else
445 if ( count == 0 ) {
446 #ifdef CHAN_STATS
447 c_blocks++;
448 #endif
449
450 insert_last( cons, node );
451 unlock( mutex_lock );
452 return false;
453 }
454
455 // Remove from buffer
456 __do_remove( *chan, *ret );
457 __set_avail_then_unlock( node, mutex_lock );
458 return true;
459}
460static inline bool unregister_select( chan_read(T) & this, select_node & node ) { return unregister_chan( *this.chan, node ); }
461static inline bool on_selected( chan_read(T) & this, select_node & node ) with(this) {
462 if ( unlikely(node.extra == 0p) ) {
463 if ( !exception_in_flight() ) __closed_remove( *chan, *ret ); // check if woken up due to closed channel
464 else return false;
465 }
466 // This is only reachable if not closed or closed exception was handled
467 return true;
468}
469
470// type used by select statement to capture a chan read as the selected operation that doesn't have a param to read to
471struct chan_read_no_ret {
472 T retval;
473 chan_read( T ) c_read;
474};
475__CFA_SELECT_GET_TYPE( chan_read_no_ret(T) );
476
477static inline void ?{}( chan_read_no_ret(T) & this, channel(T) & chan ) {
478 this.c_read{ &chan, &this.retval };
479}
480
481static inline chan_read_no_ret(T) remove( channel(T) & chan ) { chan_read_no_ret(T) c_read{ chan }; return c_read; }
482static inline bool register_select( chan_read_no_ret(T) & this, select_node & node ) {
483 this.c_read.ret = &this.retval;
484 return register_select( this.c_read, node );
485}
486static inline bool unregister_select( chan_read_no_ret(T) & this, select_node & node ) { return unregister_select( this.c_read, node ); }
487static inline bool on_selected( chan_read_no_ret(T) & this, select_node & node ) { return on_selected( this.c_read, node ); }
488
489// type used by select statement to capture a chan write as the selected operation
490struct chan_write {
491 T elem;
492 channel(T) * chan;
493};
494__CFA_SELECT_GET_TYPE( chan_write(T) );
495
496static inline void ?{}( chan_write(T) & cw, channel(T) * chan, T elem ) {
497 cw.chan = chan;
498 memcpy( (void *)&cw.elem, (void *)&elem, sizeof(T) );
499}
500static inline chan_write(T) ?<<?( channel(T) & chan, T elem ) { chan_write(T) cw{ &chan, elem }; return cw; }
501static inline chan_write(T) insert( T elem, channel(T) & chan) { chan_write(T) cw{ &chan, elem }; return cw; }
502
503static inline void __handle_select_closed_write( chan_write(T) & this, select_node & node ) with(*this.chan, this) {
504 __closed_insert( *chan, elem );
505 // if we get here then the insert succeeded
506 __make_select_node_available( node );
507}
508
509static inline bool register_select( chan_write(T) & this, select_node & node ) with(*this.chan, this) {
510 lock( mutex_lock );
511 node.extra = &elem; // set .extra so that if it == 0p later in on_selected it is due to channel close
512
513 #ifdef CHAN_STATS
514 if ( !closed ) p_ops++;
515 #endif
516
517 // special OR case handling
518 if ( !node.park_counter ) {
519 // are we special case OR and front of cons is also special case OR
520 if ( !unlikely(closed) && !cons`isEmpty && cons`first.clause_status && !cons`first.park_counter ) {
521 if ( !__make_select_node_pending( node ) ) {
522 unlock( mutex_lock );
523 return false;
524 }
525
526 if ( __handle_pending( cons, node ) ) {
527 __cons_handoff( *chan, elem );
528 __make_select_node_sat( node ); // need to to mark SAT now that we know operation is done or else threads could get stuck in __mark_select_node
529 unlock( mutex_lock );
530 return true;
531 }
532 if ( *node.clause_status == __SELECT_PENDING )
533 __make_select_node_unsat( node );
534 }
535 // check if we can complete operation. If so race to establish winner in special OR case
536 if ( count != size || !cons`isEmpty || unlikely(closed) ) {
537 if ( !__make_select_node_available( node ) ) { // we didn't win the race so give up on registering
538 unlock( mutex_lock );
539 return false;
540 }
541 }
542 }
543
544 // if closed handle
545 if ( unlikely(closed) ) {
546 unlock( mutex_lock );
547 __handle_select_closed_write( this, node );
548 return true;
549 }
550
551 // handle blocked consumer case via handoff (buffer is implicitly empty)
552 ConsEmpty: if ( !cons`isEmpty ) {
553 if ( !__handle_waituntil_OR( cons ) ) break ConsEmpty;
554 __cons_handoff( *chan, elem );
555 __set_avail_then_unlock( node, mutex_lock );
556 return true;
557 }
558
559 // insert node in list if buffer is full, work will be completed by someone else
560 if ( count == size ) {
561 #ifdef CHAN_STATS
562 p_blocks++;
563 #endif
564
565 insert_last( prods, node );
566 unlock( mutex_lock );
567 return false;
568 } // if
569
570 // otherwise carry out write either via normal insert
571 __buf_insert( *chan, elem );
572 __set_avail_then_unlock( node, mutex_lock );
573 return true;
574}
575static inline bool unregister_select( chan_write(T) & this, select_node & node ) { return unregister_chan( *this.chan, node ); }
576
577static inline bool on_selected( chan_write(T) & this, select_node & node ) with(this) {
578 if ( unlikely(node.extra == 0p) ) {
579 if ( !exception_in_flight() ) __closed_insert( *chan, elem ); // check if woken up due to closed channel
580 else return false;
581 }
582 // This is only reachable if not closed or closed exception was handled
583 return true;
584}
585
586} // forall( T )
587
588
Note: See TracBrowser for help on using the repository browser.