source: libcfa/src/concurrency/actor.hfa@ e39cfb9

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

various cleanups and improvements (shutdown flags, automatic processor count)

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