source: libcfa/src/concurrency/actor.hfa @ 1bb0170

Last change on this file since 1bb0170 was da87eaf, checked in by Peter A. Buhr <pabuhr@…>, 7 months ago

remove spurious 'this' qualification

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