source: libcfa/src/concurrency/actor.hfa @ 2c38b15

Last change on this file since 2c38b15 was 1e940de0, checked in by caparsons <caparson@…>, 17 months ago

cleanup/bugfix actors and fix virtual dtor bug

  • Property mode set to 100644
File size: 28.1 KB
Line 
1#pragma once
2
3#include <locks.hfa>
4#include <limits.hfa>
5#include <kernel.hfa>
6#include <iofwd.hfa>
7#include <virtual_dtor.hfa>
8
9#ifdef __CFA_DEBUG__
10#define CFA_DEBUG( stmt ) stmt
11#else
12#define CFA_DEBUG( stmt )
13#endif // CFA_DEBUG
14
15#define DEBUG_ABORT( cond, string ) CFA_DEBUG( if ( cond ) abort( string ) )
16
17// Define the default number of processors created in the executor. Must be greater than 0.
18#define __DEFAULT_EXECUTOR_PROCESSORS__ 2
19
20// Define the default number of threads created in the executor. Must be greater than 0.
21#define __DEFAULT_EXECUTOR_WORKERS__ 2
22
23// Define the default number of executor request-queues (mailboxes) written to by actors and serviced by the
24// actor-executor threads. Must be greater than 0.
25#define __DEFAULT_EXECUTOR_RQUEUES__ 4
26
27// Define if executor is created in a separate cluster
28#define __DEFAULT_EXECUTOR_SEPCLUS__ false
29
30#define __DEFAULT_EXECUTOR_BUFSIZE__ 10
31
32#define __STEAL 1 // workstealing toggle. Disjoint from toggles above
33
34// workstealing heuristic selection (only set one to be 1)
35// #define RAND 0
36#define SEARCH 1
37
38// show stats
39// #define ACTOR_STATS
40
41// forward decls
42struct actor;
43struct message;
44struct executor;
45
46enum allocation { Nodelete, Delete, Destroy, Finished }; // allocation status
47
48typedef allocation (*__receive_fn)(actor &, message &);
49struct request {
50    actor * base_receiver;
51    actor * receiver;
52    message * base_msg;
53    message * msg;
54    __receive_fn fn;
55    // bool stop; // commented from change to termination flag from sentinels C_TODO: remove after confirming no performance degradation
56};
57
58struct a_msg {
59    int m;
60};
61static inline void ?{}( request & this ) {
62    // this.stop = true; // default ctor makes a sentinel
63}
64static inline void ?{}( request & this, actor * base_receiver, actor * receiver, message * base_msg, message * msg, __receive_fn fn ) {
65    this.base_receiver = base_receiver;
66    this.receiver = receiver;
67    this.base_msg = base_msg;
68    this.msg = msg;
69    this.fn = fn;
70    // this.stop = false;
71}
72static inline void ?{}( request & this, request & copy ) {
73    this.receiver = copy.receiver;
74    this.msg = copy.msg;
75    this.fn = copy.fn;
76    // this.stop = copy.stop;
77}
78
79// Vector-like data structure that supports O(1) queue operations with no bound on size
80// assumes gulping behaviour (once a remove occurs, removes happen until empty beforw next insert)
81struct copy_queue {
82    request * buffer;
83    size_t count, buffer_size, index, utilized, last_size;
84};
85static inline void ?{}( copy_queue & this ) {}
86static inline void ?{}( copy_queue & this, size_t buf_size ) with(this) {
87    buffer_size = buf_size;
88    buffer = aalloc( buffer_size );
89    count = 0;
90    utilized = 0;
91    index = 0;
92    last_size = 0;
93}
94static inline void ^?{}( copy_queue & this ) with(this) {
95    DEBUG_ABORT( count != 0, "Actor system terminated with messages sent but not received\n" );
96    adelete(buffer);
97}
98
99static inline void insert( copy_queue & this, request & elem ) with(this) { // C_TODO: remove redundant send/insert once decision is made on emplace/copy
100    if ( count >= buffer_size ) { // increase arr size
101        last_size = buffer_size;
102        buffer_size = 2 * buffer_size;
103        buffer = realloc( buffer, sizeof( request ) * buffer_size );
104        /* paranoid */ verify( buffer );
105    }
106    memcpy( &buffer[count], &elem, sizeof(request) );
107    count++;
108}
109
110// once you start removing you need to remove all elements
111// it is not supported to call insert() before the array is fully empty
112static inline request & remove( copy_queue & this ) with(this) {
113    if ( count > 0 ) {
114        count--;
115        size_t old_idx = index;
116        index = count == 0 ? 0 : index + 1;
117        return buffer[old_idx];
118    }
119    request * ret = 0p;
120    return *0p;
121}
122
123// try to reclaim some memory if less than half of buffer is utilized
124static inline void reclaim( copy_queue & this ) with(this) {
125    if ( utilized >= last_size || buffer_size <= 4 ) { utilized = 0; return; }
126    utilized = 0;
127    buffer_size--;
128    buffer = realloc( buffer, sizeof( request ) * buffer_size ); // try to reclaim some memory
129}
130
131static inline bool is_empty( copy_queue & this ) with(this) { return count == 0; }
132
133struct work_queue {
134    __spinlock_t mutex_lock;
135    copy_queue * owned_queue;       // copy queue allocated and cleaned up by this work_queue
136    copy_queue * c_queue;           // current queue
137    volatile bool being_processed;  // flag to prevent concurrent processing
138    #ifdef ACTOR_STATS
139    unsigned int id;
140    size_t missed;                  // transfers skipped due to being_processed flag being up
141    #endif
142}; // work_queue
143static inline void ?{}( work_queue & this, size_t buf_size, unsigned int i ) with(this) {
144    owned_queue = alloc();      // allocated separately to avoid false sharing
145    (*owned_queue){ buf_size };
146    c_queue = owned_queue;
147    being_processed = false;
148    #ifdef ACTOR_STATS
149    id = i;
150    missed = 0;
151    #endif
152}
153
154// clean up copy_queue owned by this work_queue
155static inline void ^?{}( work_queue & this ) with(this) { delete( owned_queue ); }
156
157static inline void insert( work_queue & this, request & elem ) with(this) {
158    lock( mutex_lock __cfaabi_dbg_ctx2 );
159    insert( *c_queue, elem );
160    unlock( mutex_lock );
161} // insert
162
163static inline void transfer( work_queue & this, copy_queue ** transfer_to ) with(this) {
164    lock( mutex_lock __cfaabi_dbg_ctx2 );
165    #ifdef __STEAL
166
167    // check if queue is being processed elsewhere
168    if ( unlikely( being_processed ) ) {
169        #ifdef ACTOR_STATS
170        missed++;
171        #endif
172        unlock( mutex_lock );
173        return;
174    }
175
176    being_processed = c_queue->count != 0;
177    #endif // __STEAL
178
179    c_queue->utilized = c_queue->count;
180
181    // swap copy queue ptrs
182    copy_queue * temp = *transfer_to;
183    *transfer_to = c_queue;
184    c_queue = temp;
185    unlock( mutex_lock );
186} // transfer
187
188// needed since some info needs to persist past worker lifetimes
189struct worker_info {
190    volatile unsigned long long stamp;
191    #ifdef ACTOR_STATS
192    size_t stolen_from, try_steal, stolen, empty_stolen, failed_swaps, msgs_stolen;
193    unsigned long long processed;
194    size_t gulps;
195    #endif
196};
197static inline void ?{}( worker_info & this ) {
198    #ifdef ACTOR_STATS
199    this.stolen_from = 0;
200    this.try_steal = 0;                             // attempts to steal
201    this.stolen = 0;                                // successful steals
202    this.processed = 0;                             // requests processed
203    this.gulps = 0;                                 // number of gulps
204    this.failed_swaps = 0;                          // steal swap failures
205    this.empty_stolen = 0;                          // queues empty after steal
206    this.msgs_stolen = 0;                           // number of messages stolen
207    #endif
208    this.stamp = rdtscl();
209}
210
211// #ifdef ACTOR_STATS
212// unsigned int * stolen_arr;
213// unsigned int * replaced_queue;
214// #endif
215thread worker {
216    work_queue ** request_queues;
217    copy_queue * current_queue;
218    executor * executor_;
219    unsigned int start, range;
220    int id;
221};
222
223#ifdef ACTOR_STATS
224// aggregate counters for statistics
225size_t __total_tries = 0, __total_stolen = 0, __total_workers, __all_gulps = 0, __total_empty_stolen = 0,
226    __total_failed_swaps = 0, __all_processed = 0, __num_actors_stats = 0, __all_msgs_stolen = 0;
227#endif
228static inline void ?{}( worker & this, cluster & clu, work_queue ** request_queues, copy_queue * current_queue, executor * executor_,
229    unsigned int start, unsigned int range, int id ) {
230    ((thread &)this){ clu };
231    this.request_queues = request_queues;           // array of all queues
232    this.current_queue = current_queue;             // currently gulped queue (start with empty queue to use in swap later)
233    this.executor_ = executor_;                     // pointer to current executor
234    this.start = start;                             // start of worker's subrange of request_queues
235    this.range = range;                             // size of worker's subrange of request_queues
236    this.id = id;                                   // worker's id and index in array of workers
237}
238
239static bool no_steal = false;
240struct executor {
241    cluster * cluster;                                                      // if workers execute on separate cluster
242        processor ** processors;                                            // array of virtual processors adding parallelism for workers
243        work_queue * request_queues;                                // master array of work request queues
244    copy_queue * local_queues;                      // array of all worker local queues to avoid deletion race
245        work_queue ** worker_req_queues;                // secondary array of work queues to allow for swapping
246    worker ** workers;                                                          // array of workers executing work requests
247    worker_info * w_infos;                          // array of info about each worker
248        unsigned int nprocessors, nworkers, nrqueues;   // number of processors/threads/request queues
249        bool seperate_clus;                                                             // use same or separate cluster for executor
250    volatile bool is_shutdown;                      // flag to communicate shutdown to worker threads
251}; // executor
252
253// #ifdef ACTOR_STATS
254// __spinlock_t out_lock;
255// #endif
256static inline void ^?{}( worker & mutex this ) with(this) {
257    #ifdef ACTOR_STATS
258    __atomic_add_fetch(&__all_gulps, executor_->w_infos[id].gulps,__ATOMIC_SEQ_CST);
259    __atomic_add_fetch(&__all_processed, executor_->w_infos[id].processed,__ATOMIC_SEQ_CST);
260    __atomic_add_fetch(&__all_msgs_stolen, executor_->w_infos[id].msgs_stolen,__ATOMIC_SEQ_CST);
261    __atomic_add_fetch(&__total_tries, executor_->w_infos[id].try_steal, __ATOMIC_SEQ_CST);
262    __atomic_add_fetch(&__total_stolen, executor_->w_infos[id].stolen, __ATOMIC_SEQ_CST);
263    __atomic_add_fetch(&__total_failed_swaps, executor_->w_infos[id].failed_swaps, __ATOMIC_SEQ_CST);
264    __atomic_add_fetch(&__total_empty_stolen, executor_->w_infos[id].empty_stolen, __ATOMIC_SEQ_CST);
265
266    // per worker steal stats (uncomment alongside the lock above this routine to print)
267    // lock( out_lock __cfaabi_dbg_ctx2 );
268    // printf("Worker id: %d, processed: %llu messages, attempted %lu, stole: %lu, stolen from: %lu\n", id, processed, try_steal, stolen, __atomic_add_fetch(&executor_->w_infos[id].stolen_from, 0, __ATOMIC_SEQ_CST) );
269    // int count = 0;
270    // int count2 = 0;
271    // for ( i; range ) {
272    //     if ( replaced_queue[start + i] > 0 ){
273    //         count++;
274    //         // printf("%d: %u, ",i, replaced_queue[i]);
275    //     }
276    //     if (__atomic_add_fetch(&stolen_arr[start + i],0,__ATOMIC_SEQ_CST) > 0)
277    //         count2++;
278    // }
279    // printf("swapped with: %d of %u indices\n", count, executor_->nrqueues / executor_->nworkers );
280    // printf("%d of %u indices were stolen\n", count2, executor_->nrqueues / executor_->nworkers );
281    // unlock( out_lock );
282    #endif
283}
284
285static inline void ?{}( executor & this, unsigned int nprocessors, unsigned int nworkers, unsigned int nrqueues, bool seperate_clus, size_t buf_size ) with(this) {
286    if ( nrqueues < nworkers ) abort( "nrqueues needs to be >= nworkers\n" );
287    this.nprocessors = nprocessors;
288    this.nworkers = nworkers;
289    this.nrqueues = nrqueues;
290    this.seperate_clus = seperate_clus;
291    this.is_shutdown = false;
292
293    if ( nworkers == nrqueues )
294        no_steal = true;
295   
296    #ifdef ACTOR_STATS
297    // stolen_arr = aalloc( nrqueues );
298    // replaced_queue = aalloc( nrqueues );
299    __total_workers = nworkers;
300    #endif
301
302    if ( seperate_clus ) {
303        cluster = alloc();
304        (*cluster){};
305    } else cluster = active_cluster();
306
307    request_queues = aalloc( nrqueues );
308    worker_req_queues = aalloc( nrqueues );
309    for ( i; nrqueues ) {
310        request_queues[i]{ buf_size, i };
311        worker_req_queues[i] = &request_queues[i];
312    }
313   
314    processors = aalloc( nprocessors );
315    for ( i; nprocessors )
316        (*(processors[i] = alloc())){ *cluster };
317
318    local_queues = aalloc( nworkers );
319    workers = aalloc( nworkers );
320    w_infos = aalloc( nworkers );
321    unsigned int reqPerWorker = nrqueues / nworkers, extras = nrqueues % nworkers;
322
323    for ( i; nworkers ) {
324        w_infos[i]{};
325        local_queues[i]{ buf_size };
326    }
327
328    for ( unsigned int i = 0, start = 0, range; i < nworkers; i += 1, start += range ) {
329        range = reqPerWorker + ( i < extras ? 1 : 0 );
330        (*(workers[i] = alloc())){ *cluster, worker_req_queues, &local_queues[i], &this, start, range, i };
331    } // for
332}
333static inline void ?{}( executor & this, unsigned int nprocessors, unsigned int nworkers, unsigned int nrqueues, bool seperate_clus ) { this{ nprocessors, nworkers, nrqueues, seperate_clus, __DEFAULT_EXECUTOR_BUFSIZE__ }; }
334static inline void ?{}( executor & this, unsigned int nprocessors, unsigned int nworkers, unsigned int nrqueues ) { this{ nprocessors, nworkers, nrqueues, __DEFAULT_EXECUTOR_SEPCLUS__ }; }
335static inline void ?{}( executor & this, unsigned int nprocessors, unsigned int nworkers ) { this{ nprocessors, nworkers, __DEFAULT_EXECUTOR_RQUEUES__ }; }
336static inline void ?{}( executor & this, unsigned int nprocessors ) { this{ nprocessors, __DEFAULT_EXECUTOR_WORKERS__ }; }
337static inline void ?{}( executor & this ) { this{ __DEFAULT_EXECUTOR_PROCESSORS__ }; }
338
339static inline void ^?{}( executor & this ) with(this) {
340    // #ifdef __STEAL // commented from change to termination flag from sentinels C_TODO: remove after confirming no performance degradation
341    // request sentinels[nrqueues];
342    // for ( unsigned int i = 0; i < nrqueues; i++ ) {
343    //     insert( request_queues[i], sentinels[i] );           // force eventually termination
344    // } // for
345    // #else
346    // request sentinels[nworkers];
347    // unsigned int reqPerWorker = nrqueues / nworkers, extras = nrqueues % nworkers;
348    // for ( unsigned int i = 0, step = 0, range; i < nworkers; i += 1, step += range ) {
349    //     range = reqPerWorker + ( i < extras ? 1 : 0 );
350    //     insert( request_queues[step], sentinels[i] );                // force eventually termination
351    // } // for
352    // #endif
353    is_shutdown = true;
354
355    for ( i; nworkers )
356        delete( workers[i] );
357
358    for ( i; nprocessors ) {
359        delete( processors[i] );
360    } // for
361
362    #ifdef ACTOR_STATS
363    size_t misses = 0;
364    for ( i; nrqueues ) {
365        misses += worker_req_queues[i]->missed;
366    }
367    // adelete( stolen_arr );
368    // adelete( replaced_queue );
369    #endif
370
371    adelete( workers );
372    adelete( w_infos );
373    adelete( local_queues );
374    adelete( request_queues );
375    adelete( worker_req_queues );
376    adelete( processors );
377    if ( seperate_clus ) delete( cluster );
378
379    #ifdef ACTOR_STATS // print formatted stats
380    printf("    Actor System Stats:\n");
381    printf("\tActors Created:\t\t\t\t%lu\n\tMessages Sent:\t\t\t\t%lu\n", __num_actors_stats, __all_processed);
382    size_t avg_gulps = __all_gulps == 0 ? 0 : __all_processed / __all_gulps;
383    printf("\tGulps:\t\t\t\t\t%lu\n\tAverage Gulp Size:\t\t\t%lu\n\tMissed gulps:\t\t\t\t%lu\n", __all_gulps, avg_gulps, misses);
384    printf("\tSteal attempts:\t\t\t\t%lu\n\tSteals:\t\t\t\t\t%lu\n\tSteal failures (no candidates):\t\t%lu\n\tSteal failures (failed swaps):\t\t%lu\t Empty steals:\t\t%lu\n",
385        __total_tries, __total_stolen, __total_tries - __total_stolen - __total_failed_swaps, __total_failed_swaps, __total_empty_stolen);
386    size_t avg_steal = __total_stolen == 0 ? 0 : __all_msgs_stolen / __total_stolen;
387    printf("\tMessages stolen:\t\t\t%lu\n\tAverage steal size:\t\t\t%lu\n", __all_msgs_stolen, avg_steal);
388    #endif
389       
390}
391
392// this is a static field of executor but have to forward decl for get_next_ticket
393static size_t __next_ticket = 0;
394
395static inline size_t __get_next_ticket( executor & this ) with(this) {
396    #ifdef __CFA_DEBUG__
397    size_t temp = __atomic_fetch_add( &__next_ticket, 1, __ATOMIC_SEQ_CST) % nrqueues;
398
399    // reserve MAX for dead actors
400    if ( unlikely( temp == MAX ) ) temp = __atomic_fetch_add( &__next_ticket, 1, __ATOMIC_SEQ_CST) % nrqueues;
401    return temp;
402    #else
403    return __atomic_fetch_add( &__next_ticket, 1, __ATOMIC_RELAXED) % nrqueues;
404    #endif
405} // tickets
406
407// TODO: update globals in this file to be static fields once the static fields project is done
408static executor * __actor_executor_ = 0p;
409static bool __actor_executor_passed = false;            // was an executor passed to start_actor_system
410static size_t __num_actors_ = 0;                                        // number of actor objects in system
411static struct thread$ * __actor_executor_thd = 0p;              // used to wake executor after actors finish
412struct actor {
413    size_t ticket;                                          // executor-queue handle
414    allocation allocation_;                                         // allocation action
415    inline virtual_dtor;
416};
417
418static inline void ?{}( actor & this ) with(this) {
419    // Once an actor is allocated it must be sent a message or the actor system cannot stop. Hence, its receive
420    // member must be called to end it
421    DEBUG_ABORT( __actor_executor_ == 0p, "Creating actor before calling start_actor_system() can cause undefined behaviour.\n" );
422    allocation_ = Nodelete;
423    ticket = __get_next_ticket( *__actor_executor_ );
424    __atomic_fetch_add( &__num_actors_, 1, __ATOMIC_RELAXED );
425    #ifdef ACTOR_STATS
426    __atomic_fetch_add( &__num_actors_stats, 1, __ATOMIC_SEQ_CST );
427    #endif
428}
429
430static inline void check_actor( actor & this ) {
431    if ( this.allocation_ != Nodelete ) {
432        switch( this.allocation_ ) {
433            case Delete: delete( &this ); break;
434            case Destroy:
435                CFA_DEBUG( this.ticket = MAX; );        // mark as terminated
436                ^?{}(this);
437                break;
438            case Finished:
439                CFA_DEBUG( this.ticket = MAX; );        // mark as terminated
440                break;
441            default: ;                                                          // stop warning
442        }
443
444        if ( unlikely( __atomic_add_fetch( &__num_actors_, -1, __ATOMIC_RELAXED ) == 0 ) ) { // all actors have terminated
445            unpark( __actor_executor_thd );
446        }
447    }
448}
449
450struct message {
451    allocation allocation_;                     // allocation action
452    inline virtual_dtor;
453};
454
455static inline void ?{}( message & this ) {
456    this.allocation_ = Nodelete;
457}
458static inline void ?{}( message & this, allocation alloc ) {
459    memcpy( &this.allocation_, &alloc, sizeof(allocation) ); // optimization to elide ctor
460    DEBUG_ABORT( this.allocation_ == Finished, "The Finished allocation status is not supported for message types.\n" );
461}
462static inline void ^?{}( message & this ) with(this) {
463    CFA_DEBUG( if ( allocation_ == Nodelete ) printf("A message at location %p was allocated but never sent.\n", &this); )
464}
465
466static inline void check_message( message & this ) {
467    switch ( this.allocation_ ) {                                               // analyze message status
468        case Nodelete: CFA_DEBUG( this.allocation_ = Finished ); break;
469        case Delete: delete( &this ); break;
470        case Destroy: ^?{}( this ); break;
471        case Finished: break;
472    } // switch
473}
474static inline void set_allocation( message & this, allocation state ) {
475    this.allocation_ = state;
476}
477
478static inline void deliver_request( request & this ) {
479    DEBUG_ABORT( this.receiver->ticket == (unsigned long int)MAX, "Attempted to send message to deleted/dead actor\n" );
480    this.base_receiver->allocation_ = this.fn( *this.receiver, *this.msg );
481    check_message( *this.base_msg );
482    check_actor( *this.base_receiver );
483}
484
485// tries to atomically swap two queues and returns 0p if the swap failed
486// returns ptr to newly owned queue if swap succeeds
487static inline work_queue * try_swap_queues( worker & this, unsigned int victim_idx, unsigned int my_idx ) with(this) {
488    work_queue * my_queue = request_queues[my_idx];
489    work_queue * other_queue = request_queues[victim_idx];
490
491    // if either queue is 0p then they are in the process of being stolen
492    if ( other_queue == 0p ) return 0p;
493
494    // try to set our queue ptr to be 0p. If it fails someone moved our queue so return false
495    if ( !__atomic_compare_exchange_n( &request_queues[my_idx], &my_queue, 0p, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) )
496        return 0p;
497
498    // try to set other queue ptr to be our queue ptr. If it fails someone moved the other queue so fix up then return false
499    if ( !__atomic_compare_exchange_n( &request_queues[victim_idx], &other_queue, my_queue, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) ) {
500        /* paranoid */ verify( request_queues[my_idx] == 0p );
501        request_queues[my_idx] = my_queue; // reset my queue ptr back to appropriate val
502        return 0p;
503    }
504
505    // we have successfully swapped and since our queue is 0p no one will touch it so write back new queue ptr non atomically
506    request_queues[my_idx] = other_queue; // last write does not need to be atomic
507    return other_queue;
508}
509
510// once a worker to steal from has been chosen, choose queue to steal from
511static inline void choose_queue( worker & this, unsigned int victim_id, unsigned int swap_idx ) with(this) {
512    // have to calculate victim start and range since victim may be deleted before us in shutdown
513    const unsigned int queues_per_worker = executor_->nrqueues / executor_->nworkers;
514    const unsigned int extras = executor_->nrqueues % executor_->nworkers;
515    unsigned int vic_start, vic_range;
516    if ( extras > victim_id  ) {
517        vic_range = queues_per_worker + 1;
518        vic_start = vic_range * victim_id;
519    } else {
520        vic_start = extras + victim_id * queues_per_worker;
521        vic_range = queues_per_worker;
522    }
523    unsigned int start_idx = prng( vic_range );
524
525    unsigned int tries = 0;
526    work_queue * curr_steal_queue;
527
528    for ( unsigned int i = start_idx; tries < vic_range; i = (i + 1) % vic_range ) {
529        tries++;
530        curr_steal_queue = request_queues[ i + vic_start ];
531        // avoid empty queues and queues that are being operated on
532        if ( curr_steal_queue == 0p || curr_steal_queue->being_processed || is_empty( *curr_steal_queue->c_queue ) )
533            continue;
534
535        #ifdef ACTOR_STATS
536        curr_steal_queue = try_swap_queues( this, i + vic_start, swap_idx );
537        if ( curr_steal_queue ) {
538            executor_->w_infos[id].msgs_stolen += curr_steal_queue->c_queue->count;
539            executor_->w_infos[id].stolen++;
540            if ( is_empty( *curr_steal_queue->c_queue ) ) executor_->w_infos[id].empty_stolen++;
541            // __atomic_add_fetch(&executor_->w_infos[victim_id].stolen_from, 1, __ATOMIC_RELAXED);
542            // replaced_queue[swap_idx]++;
543            // __atomic_add_fetch(&stolen_arr[ i + vic_start ], 1, __ATOMIC_RELAXED);
544        } else {
545            executor_->w_infos[id].failed_swaps++;
546        }
547        #else
548        curr_steal_queue = try_swap_queues( this, i + vic_start, swap_idx );
549        #endif // ACTOR_STATS
550
551        return;
552    }
553
554    return;
555}
556
557// choose a worker to steal from
558static inline void steal_work( worker & this, unsigned int swap_idx ) with(this) {
559    #if RAND
560    unsigned int victim = prng( executor_->nworkers );
561    if ( victim == id ) victim = ( victim + 1 ) % executor_->nworkers;
562    choose_queue( this, victim, swap_idx );
563    #elif SEARCH
564    unsigned long long min = MAX; // smaller timestamp means longer since service
565    int min_id = 0; // use ints not uints to avoid integer underflow without hacky math
566    int n_workers = executor_->nworkers;
567    unsigned long long curr_stamp;
568    int scount = 1;
569    for ( int i = (id + 1) % n_workers; scount < n_workers; i = (i + 1) % n_workers, scount++ ) {
570        curr_stamp = executor_->w_infos[i].stamp;
571        if ( curr_stamp < min ) {
572            min = curr_stamp;
573            min_id = i;
574        }
575    }
576    choose_queue( this, min_id, swap_idx );
577    #endif
578}
579
580#define CHECK_TERMINATION if ( unlikely( executor_->is_shutdown ) ) break Exit
581void main( worker & this ) with(this) {
582    // #ifdef ACTOR_STATS
583    // for ( i; executor_->nrqueues ) {
584    //     replaced_queue[i] = 0;
585    //     __atomic_store_n( &stolen_arr[i], 0, __ATOMIC_SEQ_CST );
586    // }
587    // #endif
588
589    // threshold of empty queues we see before we go stealing
590    const unsigned int steal_threshold = 2 * range;
591
592    // Store variable data here instead of worker struct to avoid any potential false sharing
593    unsigned int empty_count = 0;
594    request & req;
595    work_queue * curr_work_queue;
596
597    Exit:
598    for ( unsigned int i = 0;; i = (i + 1) % range ) { // cycle through set of request buffers
599        curr_work_queue = request_queues[i + start];
600       
601        // check if queue is empty before trying to gulp it
602        if ( is_empty( *curr_work_queue->c_queue ) ) {
603            #ifdef __STEAL
604            empty_count++;
605            if ( empty_count < steal_threshold ) continue;
606            #else
607            continue;
608            #endif
609        }
610        transfer( *curr_work_queue, &current_queue );
611        #ifdef ACTOR_STATS
612        executor_->w_infos[id].gulps++;
613        #endif // ACTOR_STATS
614        #ifdef __STEAL
615        if ( is_empty( *current_queue ) ) {
616            if ( unlikely( no_steal ) ) { CHECK_TERMINATION; continue; } // C_TODO: if this impacts static/dynamic perf refactor check
617            empty_count++;
618            if ( empty_count < steal_threshold ) continue;
619            empty_count = 0;
620
621            CHECK_TERMINATION; // check for termination
622
623            __atomic_store_n( &executor_->w_infos[id].stamp, rdtscl(), __ATOMIC_RELAXED );
624           
625            #ifdef ACTOR_STATS
626            executor_->w_infos[id].try_steal++;
627            #endif // ACTOR_STATS
628           
629            steal_work( this, start + prng( range ) );
630            continue;
631        }
632        #endif // __STEAL
633        while ( ! is_empty( *current_queue ) ) {
634            #ifdef ACTOR_STATS
635            executor_->w_infos[id].processed++;
636            #endif
637            &req = &remove( *current_queue );
638            if ( !&req ) continue;
639            // if ( req.stop ) break Exit;
640            deliver_request( req );
641        }
642        #ifdef __STEAL
643        curr_work_queue->being_processed = false; // set done processing
644        empty_count = 0; // we found work so reset empty counter
645        #endif
646       
647        // potentially reclaim some of the current queue's vector space if it is unused
648        reclaim( *current_queue );
649    } // for
650}
651
652static inline void send( executor & this, request & req, unsigned long int ticket ) with(this) {
653    insert( request_queues[ticket], req);
654}
655
656static inline void send( actor & this, request & req ) {
657    DEBUG_ABORT( this.ticket == (unsigned long int)MAX, "Attempted to send message to deleted/dead actor\n" );
658    send( *__actor_executor_, req, this.ticket );
659}
660
661static inline void __reset_stats() {
662    #ifdef ACTOR_STATS
663    __total_tries = 0;
664    __total_stolen = 0;
665    __all_gulps = 0;
666    __total_failed_swaps = 0;
667    __total_empty_stolen = 0;
668    __all_processed = 0;
669    __num_actors_stats = 0;
670    __all_msgs_stolen = 0;
671    #endif
672}
673
674static inline void start_actor_system( size_t num_thds ) {
675    __reset_stats();
676    __actor_executor_thd = active_thread();
677    __actor_executor_ = alloc();
678    (*__actor_executor_){ 0, num_thds, num_thds == 1 ? 1 : num_thds * 16 };
679}
680
681// TODO: potentially revisit getting number of processors
682//  ( currently the value stored in active_cluster()->procs.total is often stale
683//  and doesn't reflect how many procs are allocated )
684// static inline void start_actor_system() { start_actor_system( active_cluster()->procs.total ); }
685static inline void start_actor_system() { start_actor_system( 1 ); }
686
687static inline void start_actor_system( executor & this ) {
688    __reset_stats();
689    __actor_executor_thd = active_thread();
690    __actor_executor_ = &this;
691    __actor_executor_passed = true;
692}
693
694static inline void stop_actor_system() {
695    park( ); // will receive signal when actor system is finished
696
697    if ( !__actor_executor_passed ) delete( __actor_executor_ );
698    __actor_executor_ = 0p;
699    __actor_executor_thd = 0p;
700    __next_ticket = 0;
701    __actor_executor_passed = false;
702}
703
704// Default messages to send to any actor to change status
705// assigned at creation to __base_msg_finished to avoid unused message warning
706message __base_msg_finished @= { .allocation_ : Finished };
707struct __delete_msg_t { inline message; } delete_msg = __base_msg_finished;
708struct __destroy_msg_t { inline message; } destroy_msg = __base_msg_finished;
709struct __finished_msg_t { inline message; } finished_msg = __base_msg_finished;
710
711allocation receive( actor & this, __delete_msg_t & msg ) { return Delete; }
712allocation receive( actor & this, __destroy_msg_t & msg ) { return Destroy; }
713allocation receive( actor & this, __finished_msg_t & msg ) { return Finished; }
714
Note: See TracBrowser for help on using the repository browser.