| 1 | #pragma once
 | 
|---|
| 2 | 
 | 
|---|
| 3 | #include "containers/list.hfa"
 | 
|---|
| 4 | #include <stdint.h>
 | 
|---|
| 5 | #include <kernel.hfa>
 | 
|---|
| 6 | #include <locks.hfa>
 | 
|---|
| 7 | 
 | 
|---|
| 8 | struct select_node {
 | 
|---|
| 9 |     thread$ * blocked_thread;
 | 
|---|
| 10 |     void ** race_flag;
 | 
|---|
| 11 |     inline dlink(select_node);
 | 
|---|
| 12 | };
 | 
|---|
| 13 | P9_EMBEDDED( select_node, dlink(select_node) )
 | 
|---|
| 14 | 
 | 
|---|
| 15 | void ?{}( select_node & this ) {
 | 
|---|
| 16 |     this.blocked_thread = 0p;
 | 
|---|
| 17 |     this.race_flag = 0p;
 | 
|---|
| 18 | }
 | 
|---|
| 19 | 
 | 
|---|
| 20 | void ?{}( select_node & this, thread$ * blocked_thread ) {
 | 
|---|
| 21 |     this.blocked_thread = blocked_thread;
 | 
|---|
| 22 |     this.race_flag = 0p;
 | 
|---|
| 23 | }
 | 
|---|
| 24 | 
 | 
|---|
| 25 | void ?{}( select_node & this, thread$ * blocked_thread, void ** race_flag ) {
 | 
|---|
| 26 |     this.blocked_thread = blocked_thread;
 | 
|---|
| 27 |     this.race_flag = race_flag;
 | 
|---|
| 28 | }
 | 
|---|
| 29 | 
 | 
|---|
| 30 | void ^?{}( select_node & this ) {}
 | 
|---|
| 31 | 
 | 
|---|
| 32 | 
 | 
|---|
| 33 | //-----------------------------------------------------------------------------
 | 
|---|
| 34 | // is_selectable
 | 
|---|
| 35 | trait is_selectable(T & | sized(T)) {
 | 
|---|
| 36 |     // For registering a select on a selectable concurrency primitive
 | 
|---|
| 37 |     // return 0p if primitive not accessible yet
 | 
|---|
| 38 |     // return 1p if primitive gets acquired
 | 
|---|
| 39 |     // return 2p if primitive is accessible but some other primitive won the race
 | 
|---|
| 40 |     // C_TODO: add enum for return values
 | 
|---|
| 41 |     void * register_select( T &, select_node & );
 | 
|---|
| 42 | 
 | 
|---|
| 43 |     void unregister_select( T &, select_node &  );
 | 
|---|
| 44 | };
 | 
|---|
| 45 | 
 | 
|---|
| 46 | static inline bool install_select_winner( select_node & this, void * primitive_ptr ) with(this) {
 | 
|---|
| 47 |     // temporary needed for atomic instruction
 | 
|---|
| 48 |     void * cmp_flag = 0p;
 | 
|---|
| 49 |     
 | 
|---|
| 50 |     // if we dont win the selector race we need to potentially 
 | 
|---|
| 51 |     //   ignore this node and move to the next one so we return accordingly
 | 
|---|
| 52 |     if ( *race_flag != 0p || 
 | 
|---|
| 53 |         !__atomic_compare_exchange_n(
 | 
|---|
| 54 |             race_flag, 
 | 
|---|
| 55 |             &cmp_flag, 
 | 
|---|
| 56 |             primitive_ptr, 
 | 
|---|
| 57 |             false,
 | 
|---|
| 58 |             __ATOMIC_SEQ_CST,
 | 
|---|
| 59 |             __ATOMIC_SEQ_CST
 | 
|---|
| 60 |         )
 | 
|---|
| 61 |     ) return false; // lost race and some other node triggered select
 | 
|---|
| 62 |     return true; // won race so this node is what the select proceeds with
 | 
|---|
| 63 | }
 | 
|---|