File: ipc_server.cpp

package info (click to toggle)
onetbb 2022.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 19,444 kB
  • sloc: cpp: 129,228; ansic: 9,745; python: 808; xml: 183; objc: 176; makefile: 66; sh: 66; awk: 41; javascript: 37
file content (1136 lines) | stat: -rw-r--r-- 39,695 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
/*
    Copyright (c) 2017-2022 Intel Corporation

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#include <atomic>
#include <cstring>
#include <cstdlib>

#include "../../src/tbb/rml_tbb.h"
#include "../../src/tbb/rml_thread_monitor.h"
#include "../../src/tbb/scheduler_common.h"
#include "../../src/tbb/governor.h"
#include "../../src/tbb/misc.h"
#include "tbb/cache_aligned_allocator.h"

#include "ipc_utils.h"

#include <fcntl.h>
#include <stdlib.h>

namespace rml {
namespace internal {

static const char* IPC_ENABLE_VAR_NAME = "IPC_ENABLE";

typedef versioned_object::version_type version_type;

extern "C" factory::status_type __RML_open_factory(factory& f, version_type& /*server_version*/, version_type /*client_version*/) {
    if( !tbb::internal::rml::get_enable_flag( IPC_ENABLE_VAR_NAME ) ) {
        return factory::st_incompatible;
    }

    // Hack to keep this library from being closed
    static std::atomic<bool> one_time_flag{false};
    bool expected = false;

    if( one_time_flag.compare_exchange_strong(expected, true) ) {
        __TBB_ASSERT( (size_t)f.library_handle!=factory::c_dont_unload, nullptr );
#if _WIN32||_WIN64
        f.library_handle = reinterpret_cast<HMODULE>(factory::c_dont_unload);
#else
        f.library_handle = reinterpret_cast<void*>(factory::c_dont_unload);
#endif
    }
    // End of hack

    return factory::st_success;
}

extern "C" void __RML_close_factory(factory& /*f*/) {
}

class ipc_thread_monitor : public tbb::detail::r1::rml::internal::thread_monitor {
public:
    ipc_thread_monitor() : thread_monitor() {}

#if USE_WINTHREAD
#elif USE_PTHREAD
    static handle_type launch(thread_routine_type thread_routine, void* arg, size_t stack_size);
#endif
};

#if USE_WINTHREAD
#elif USE_PTHREAD
inline ipc_thread_monitor::handle_type ipc_thread_monitor::launch(void* (*thread_routine)(void*), void* arg, size_t stack_size) {
    pthread_attr_t s;
    if( pthread_attr_init( &s ) ) return 0;
    if( stack_size>0 ) {
        if( pthread_attr_setstacksize( &s, stack_size ) ) return 0;
    }
    pthread_t handle;
    if( pthread_create( &handle, &s, thread_routine, arg ) ) return 0;
    if( pthread_attr_destroy( &s ) ) return 0;
    return handle;
}
#endif

}} // rml::internal

using rml::internal::ipc_thread_monitor;
using tbb::internal::rml::get_shared_name;

namespace tbb {
namespace detail {

namespace r1 {
bool terminate_on_exception() {
    return false;
}
}

namespace rml {

typedef ipc_thread_monitor::handle_type thread_handle;

class ipc_server;

static const char* IPC_MAX_THREADS_VAR_NAME = "MAX_THREADS";
static const char* IPC_ACTIVE_SEM_PREFIX = "/__IPC_active";
static const char* IPC_STOP_SEM_PREFIX = "/__IPC_stop";
static const char* IPC_ACTIVE_SEM_VAR_NAME = "IPC_ACTIVE_SEMAPHORE";
static const char* IPC_STOP_SEM_VAR_NAME = "IPC_STOP_SEMAPHORE";
static const mode_t IPC_SEM_MODE = 0660;

static std::atomic<int> my_global_thread_count;
using tbb_client = tbb::detail::r1::rml::tbb_client;
using tbb_server = tbb::detail::r1::rml::tbb_server;
using tbb_factory = tbb::detail::r1::rml::tbb_factory;

using tbb::detail::r1::runtime_warning;

char* get_sem_name(const char* name, const char* prefix) {
    __TBB_ASSERT(name != nullptr, nullptr);
    __TBB_ASSERT(prefix != nullptr, nullptr);
    char* value = std::getenv(name);
    std::size_t len = value == nullptr ? 0 : std::strlen(value);
    if (len > 0) {
        // TODO: consider returning the original string instead of the copied string.
        char* sem_name = new char[len + 1];
        __TBB_ASSERT(sem_name != nullptr, nullptr);
        std::strncpy(sem_name, value, len+1);
        __TBB_ASSERT(sem_name[len] == 0, nullptr);
        return sem_name;
    } else {
        return get_shared_name(prefix);
    }
}

char* get_active_sem_name() {
    return get_sem_name(IPC_ACTIVE_SEM_VAR_NAME, IPC_ACTIVE_SEM_PREFIX);
}

char* get_stop_sem_name() {
    return get_sem_name(IPC_STOP_SEM_VAR_NAME, IPC_STOP_SEM_PREFIX);
}

static void release_thread_sem(sem_t* my_sem) {
    int old = my_global_thread_count.load(std::memory_order_relaxed);
    do {
        if( old<=0 ) return;
    } while( !my_global_thread_count.compare_exchange_strong(old, old-1) );
    if( old>0 ) {
        sem_post( my_sem );
    }
}

void set_sem_name(const char* name, const char* prefix) {
    __TBB_ASSERT(name != nullptr, nullptr);
    __TBB_ASSERT(prefix != nullptr, nullptr);
    const char* postfix = "_XXXXXX";
    std::size_t plen = std::strlen(prefix);
    std::size_t xlen = std::strlen(postfix);
    char* templ = new char[plen + xlen + 1];
    __TBB_ASSERT(templ != nullptr, nullptr);
    strncpy(templ, prefix, plen+1);
    __TBB_ASSERT(templ[plen] == 0, nullptr);
    strncat(templ, postfix, xlen + 1);
    __TBB_ASSERT(std::strlen(templ) == plen + xlen + 1, nullptr);
    // TODO: consider using mkstemp instead of mktemp.
    char* sem_name = mktemp(templ);
    if (sem_name != nullptr) {
        int status = setenv(name, sem_name,  /*overwrite*/ 1);
        __TBB_ASSERT_EX(status == 0, nullptr);
    }
    delete[] templ;
}

extern "C" void set_active_sem_name() {
    set_sem_name(IPC_ACTIVE_SEM_VAR_NAME, IPC_ACTIVE_SEM_PREFIX);
}

extern "C" void set_stop_sem_name() {
    set_sem_name(IPC_STOP_SEM_VAR_NAME, IPC_STOP_SEM_PREFIX);
}

extern "C" void release_resources() {
    if( my_global_thread_count.load(std::memory_order_acquire)!=0 ) {
        char* active_sem_name = get_active_sem_name();
        sem_t* my_active_sem = sem_open( active_sem_name, O_CREAT );
        __TBB_ASSERT( my_active_sem, "Unable to open active threads semaphore" );
        delete[] active_sem_name;

        do {
            release_thread_sem( my_active_sem );
        } while( my_global_thread_count.load(std::memory_order_acquire)!=0 );
    }
}

extern "C" void release_semaphores() {
    int status = 0;
    char* sem_name = nullptr;

    sem_name = get_active_sem_name();
    if( sem_name==nullptr ) {
        runtime_warning("Can not get RML semaphore name");
        return;
    }
    status = sem_unlink( sem_name );
    if( status!=0 ) {
        if( errno==ENOENT ) {
            /* There is no semaphore with the given name, nothing to do */
        } else {
            runtime_warning("Can not release RML semaphore");
            return;
        }
    }
    delete[] sem_name;

    sem_name = get_stop_sem_name();
    if( sem_name==nullptr ) {
        runtime_warning( "Can not get RML semaphore name" );
        return;
    }
    status = sem_unlink( sem_name );
    if( status!=0 ) {
        if( errno==ENOENT ) {
            /* There is no semaphore with the given name, nothing to do */
        } else {
            runtime_warning("Can not release RML semaphore");
            return;
        }
    }
    delete[] sem_name;
}

class ipc_worker: no_copy {
protected:
    //! State in finite-state machine that controls the worker.
    /** State diagram:
                    /----------stop---\
                    |           ^     |
                    V           |     |
        init --> starting --> normal  |
          |         |           |     |
          |         V           |     |
          \------> quit <-------/<----/
      */
    enum state_t {
        //! *this is initialized
        st_init,
        //! *this has associated thread that is starting up.
        st_starting,
        //! Associated thread is doing normal life sequence.
        st_normal,
        //! Associated thread is stopped but can be started again.
        st_stop,
        //! Associated thread has ended normal life sequence and promises to never touch *this again.
        st_quit
    };
    std::atomic<state_t> my_state;

    //! Associated server
    ipc_server& my_server;

    //! Associated client
    tbb_client& my_client;

    //! index used for avoiding the 64K aliasing problem
    const size_t my_index;

    //! Monitor for sleeping when there is no work to do.
    /** The invariant that holds for sleeping workers is:
        "my_slack<=0 && my_state==st_normal && I am on server's list of asleep threads" */
    ipc_thread_monitor my_thread_monitor;

    //! Handle of the OS thread associated with this worker
    thread_handle my_handle;

    //! Link for list of workers that are sleeping or have no associated thread.
    ipc_worker* my_next;

    friend class ipc_server;

    //! Actions executed by the associated thread
    void run();

    //! Wake up associated thread (or launch a thread if there is none)
    bool wake_or_launch();

    //! Called by a thread (usually not the associated thread) to commence termination.
    void start_shutdown(bool join);

    //! Called by a thread (usually not the associated thread) to commence stopping.
    void start_stopping(bool join);

    static __RML_DECL_THREAD_ROUTINE thread_routine(void* arg);

    static void release_handle(thread_handle my_handle, bool join);

protected:
    ipc_worker(ipc_server& server, tbb_client& client, const size_t i) :
        my_server(server),
        my_client(client),
        my_index(i)
    {
        my_state = st_init;
    }
};

//TODO: cannot bind to nfs_size from allocator.cpp since nfs_size is constexpr defined in another translation unit
constexpr static size_t cache_line_sz = 128;

#if _MSC_VER && !defined(__INTEL_COMPILER)
    // Suppress overzealous compiler warnings about uninstantiable class
    #pragma warning(push)
    #pragma warning(disable:4510 4610)
#endif
class padded_ipc_worker: public ipc_worker {
    char pad[cache_line_sz - sizeof(ipc_worker)%cache_line_sz];
public:
    padded_ipc_worker(ipc_server& server, tbb_client& client, const size_t i)
    : ipc_worker( server,client,i ) { suppress_unused_warning(pad); }
};
#if _MSC_VER && !defined(__INTEL_COMPILER)
    #pragma warning(pop)
#endif

class ipc_waker : public padded_ipc_worker {
private:
    static __RML_DECL_THREAD_ROUTINE thread_routine(void* arg);
    void run();
    bool wake_or_launch();

    friend class ipc_server;

public:
    ipc_waker(ipc_server& server, tbb_client& client, const size_t i)
    : padded_ipc_worker( server, client, i ) {}
};

class ipc_stopper : public padded_ipc_worker {
private:
    static __RML_DECL_THREAD_ROUTINE thread_routine(void* arg);
    void run();
    bool wake_or_launch();

    friend class ipc_server;

public:
    ipc_stopper(ipc_server& server, tbb_client& client, const size_t i)
    : padded_ipc_worker( server, client, i ) {}
};

class ipc_server: public tbb_server, no_copy {
private:
    tbb_client& my_client;
    //! Maximum number of threads to be created.
    /** Threads are created lazily, so maximum might not actually be reached. */
    tbb_client::size_type my_n_thread;

    //! Stack size for each thread. */
    const size_t my_stack_size;

    //! Number of jobs that could use their associated thread minus number of active threads.
    /** If negative, indicates oversubscription.
        If positive, indicates that more threads should run.
        Can be lowered asynchronously, but must be raised only while holding my_asleep_list_mutex,
        because raising it impacts the invariant for sleeping threads. */
    std::atomic<int> my_slack;

    //! Counter used to determine when to delete this.
    std::atomic<int> my_ref_count;

    padded_ipc_worker* my_thread_array;

    //! List of workers that are asleep or committed to sleeping until notified by another thread.
    std::atomic<ipc_worker*> my_asleep_list_root;

    //! Protects my_asleep_list_root
    typedef scheduler_mutex_type asleep_list_mutex_type;
    asleep_list_mutex_type my_asleep_list_mutex;

    //! Should server wait workers while terminate
    const bool my_join_workers;

    //! Service thread for waking of workers
    ipc_waker* my_waker;

    //! Service thread to stop threads
    ipc_stopper* my_stopper;

    //! Semaphore to account active threads
    sem_t* my_active_sem;

    //! Semaphore to account stop threads
    sem_t* my_stop_sem;

#if TBB_USE_ASSERT
    std::atomic<int> my_net_slack_requests;
#endif /* TBB_USE_ASSERT */

    //! Wake up to two sleeping workers, if there are any sleeping.
    /** The call is used to propagate a chain reaction where each thread wakes up two threads,
        which in turn each wake up two threads, etc. */
    void propagate_chain_reaction() {
        // First test of a double-check idiom.  Second test is inside wake_some(0).
        if( my_slack.load(std::memory_order_acquire)>0 ) {
            int active_threads = 0;
            if( try_get_active_thread() ) {
                ++active_threads;
                if( try_get_active_thread() ) {
                    ++active_threads;
                }
                wake_some( 0, active_threads );
            }
        }
    }

    //! Try to add t to list of sleeping workers
    bool try_insert_in_asleep_list(ipc_worker& t);

    //! Try to add t to list of sleeping workers even if there is some work to do
    bool try_insert_in_asleep_list_forced(ipc_worker& t);

    //! Equivalent of adding additional_slack to my_slack and waking up to 2 threads if my_slack permits.
    void wake_some(int additional_slack, int active_threads);

    //! Equivalent of adding additional_slack to my_slack and waking up to 1 thread if my_slack permits.
    void wake_one_forced(int additional_slack);

    //! Stop one thread from asleep list
    bool stop_one();

    //! Wait for active thread
    bool wait_active_thread();

    //! Try to get active thread
    bool try_get_active_thread();

    //! Release active thread
    void release_active_thread();

    //! Wait for thread to stop
    bool wait_stop_thread();

    //! Add thread to stop list
    void add_stop_thread();

    void remove_server_ref() {
        if( --my_ref_count==0 ) {
            my_client.acknowledge_close_connection();
            this->~ipc_server();
            tbb::cache_aligned_allocator<ipc_server>().deallocate( this, 1 );
        }
    }

    friend class ipc_worker;
    friend class ipc_waker;
    friend class ipc_stopper;
public:
    ipc_server(tbb_client& client);
    virtual ~ipc_server();

    version_type version() const override {
        return 0;
    }

    void request_close_connection(bool /*exiting*/) override {
        my_waker->start_shutdown(false);
        my_stopper->start_shutdown(false);
        for( size_t i=0; i<my_n_thread; ++i )
            my_thread_array[i].start_shutdown( my_join_workers );
        remove_server_ref();
    }

    void yield() override {d0::yield();}

    void independent_thread_number_changed(int) override { __TBB_ASSERT( false, nullptr ); }

    unsigned default_concurrency() const override { return my_n_thread - 1; }

    void adjust_job_count_estimate(int delta) override;

#if _WIN32||_WIN64
    void register_external_thread(::rml::server::execution_resource_t&) override {}
    void unregister_external_thread(::rml::server::execution_resource_t) override {}
#endif /* _WIN32||_WIN64 */
};

//------------------------------------------------------------------------
// Methods of ipc_worker
//------------------------------------------------------------------------
#if _MSC_VER && !defined(__INTEL_COMPILER)
    // Suppress overzealous compiler warnings about an initialized variable 'sink_for_alloca' not referenced
    #pragma warning(push)
    #pragma warning(disable:4189)
#endif
#if __MINGW32__ && __GNUC__==4 &&__GNUC_MINOR__>=2 && !__MINGW64__
// ensure that stack is properly aligned
__attribute__((force_align_arg_pointer))
#endif
__RML_DECL_THREAD_ROUTINE ipc_worker::thread_routine(void* arg) {
    ipc_worker* self = static_cast<ipc_worker*>(arg);
    AVOID_64K_ALIASING( self->my_index );
    self->run();
    return 0;
}
#if _MSC_VER && !defined(__INTEL_COMPILER)
    #pragma warning(pop)
#endif

void ipc_worker::release_handle(thread_handle handle, bool join) {
    if( join )
        ipc_thread_monitor::join( handle );
    else
        ipc_thread_monitor::detach_thread( handle );
}

void ipc_worker::start_shutdown(bool join) {
    state_t s = my_state.load(std::memory_order_relaxed);

    do {
        __TBB_ASSERT( s!=st_quit, nullptr );
    } while( !my_state.compare_exchange_strong( s, st_quit ) );
    if( s==st_normal || s==st_starting ) {
        // May have invalidated invariant for sleeping, so wake up the thread.
        // Note that the notify() here occurs without maintaining invariants for my_slack.
        // It does not matter, because my_state==st_quit overrides checking of my_slack.
        my_thread_monitor.notify();
        // Do not need release handle in st_init state,
        // because in this case the thread wasn't started yet.
        // For st_starting release is done at launch site.
        if( s==st_normal )
            release_handle( my_handle, join );
    }
}

void ipc_worker::start_stopping(bool join) {
    state_t s = my_state.load(std::memory_order_relaxed);

    while( !my_state.compare_exchange_strong( s, st_quit ) ) {};
    if( s==st_normal || s==st_starting ) {
        // May have invalidated invariant for sleeping, so wake up the thread.
        // Note that the notify() here occurs without maintaining invariants for my_slack.
        // It does not matter, because my_state==st_quit overrides checking of my_slack.
        my_thread_monitor.notify();
        // Do not need release handle in st_init state,
        // because in this case the thread wasn't started yet.
        // For st_starting release is done at launch site.
        if( s==st_normal )
            release_handle( my_handle, join );
    }
}

void ipc_worker::run() {
    my_server.propagate_chain_reaction();

    // Transiting to st_normal here would require setting my_handle,
    // which would create race with the launching thread and
    // complications in handle management on Windows.

    ::rml::job& j = *my_client.create_one_job();
    state_t state = my_state.load(std::memory_order_acquire);
    while( state!=st_quit && state!=st_stop ) {
        if( my_server.my_slack>=0 ) {
            my_client.process(j);
        } else {
            // Check/set the invariant for sleeping
            state = my_state.load(std::memory_order_seq_cst);
            if( state!=st_quit && state!=st_stop && my_server.try_insert_in_asleep_list(*this) ) {
                if( my_server.my_n_thread > 1 ) my_server.release_active_thread();
                my_thread_monitor.wait();
                my_server.propagate_chain_reaction();
            }
        }
        // memory_order_seq_cst to be strictly ordered after thread_monitor::wait
        state = my_state.load(std::memory_order_seq_cst);
    }
    my_client.cleanup(j);

    my_server.remove_server_ref();
}

inline bool ipc_worker::wake_or_launch() {
    state_t excepted_stop = st_stop, expected_init = st_init;
    if( ( my_state.load(std::memory_order_acquire)==st_init && my_state.compare_exchange_strong( expected_init, st_starting ) ) ||
        ( my_state.load(std::memory_order_acquire)==st_stop && my_state.compare_exchange_strong( excepted_stop, st_starting ) ) ) {
        // after this point, remove_server_ref() must be done by created thread
#if USE_WINTHREAD
        my_handle = ipc_thread_monitor::launch( thread_routine, this, my_server.my_stack_size, &this->my_index );
#elif USE_PTHREAD
        {
        affinity_helper fpa;
        fpa.protect_affinity_mask( /*restore_process_mask=*/true );
        my_handle = ipc_thread_monitor::launch( thread_routine, this, my_server.my_stack_size );
        if( my_handle == 0 ) {
            // Unable to create new thread for process
            // However, this is expected situation for the use cases of this coordination server
            state_t s = st_starting;
            my_state.compare_exchange_strong( s, st_init );
            if (st_starting != s) {
                // Do shutdown during startup. my_handle can't be released
                // by start_shutdown, because my_handle value might be not set yet
                // at time of transition from st_starting to st_quit.
                __TBB_ASSERT( s==st_quit, nullptr );
                release_handle( my_handle, my_server.my_join_workers );
            }
            return false;
        } else {
            my_server.my_ref_count++;
        }
        // Implicit destruction of fpa resets original affinity mask.
        }
#endif /* USE_PTHREAD */
        state_t s = st_starting;
        my_state.compare_exchange_strong( s, st_normal );
        if( st_starting!=s ) {
            // Do shutdown during startup. my_handle can't be released
            // by start_shutdown, because my_handle value might be not set yet
            // at time of transition from st_starting to st_quit.
            __TBB_ASSERT( s==st_quit, nullptr );
            release_handle( my_handle, my_server.my_join_workers );
        }
    }
    else {
        my_thread_monitor.notify();
    }

    return true;
}

//------------------------------------------------------------------------
// Methods of ipc_waker
//------------------------------------------------------------------------
#if _MSC_VER && !defined(__INTEL_COMPILER)
    // Suppress overzealous compiler warnings about an initialized variable 'sink_for_alloca' not referenced
    #pragma warning(push)
    #pragma warning(disable:4189)
#endif
#if __MINGW32__ && __GNUC__==4 &&__GNUC_MINOR__>=2 && !__MINGW64__
// ensure that stack is properly aligned
__attribute__((force_align_arg_pointer))
#endif
__RML_DECL_THREAD_ROUTINE ipc_waker::thread_routine(void* arg) {
    ipc_waker* self = static_cast<ipc_waker*>(arg);
    AVOID_64K_ALIASING( self->my_index );
    self->run();
    return 0;
}
#if _MSC_VER && !defined(__INTEL_COMPILER)
    #pragma warning(pop)
#endif

void ipc_waker::run() {
    // Transiting to st_normal here would require setting my_handle,
    // which would create race with the launching thread and
    // complications in handle management on Windows.

    // memory_order_seq_cst to be strictly ordered after thread_monitor::wait on the next iteration
    while( my_state.load(std::memory_order_seq_cst)!=st_quit ) {
        bool have_to_sleep = false;
        if( my_server.my_slack.load(std::memory_order_acquire)>0 ) {
            if( my_server.wait_active_thread() ) {
                if( my_server.my_slack.load(std::memory_order_acquire)>0 ) {
                    my_server.wake_some( 0, 1 );
                } else {
                    my_server.release_active_thread();
                    have_to_sleep = true;
                }
            }
        } else {
            have_to_sleep = true;
        }
        if( have_to_sleep ) {
            // Check/set the invariant for sleeping
            if( my_server.my_slack.load(std::memory_order_acquire)<0 ) {
                my_thread_monitor.wait();
            }
        }
    }

    my_server.remove_server_ref();
}

inline bool ipc_waker::wake_or_launch() {
    state_t excepted = st_init;
    if( ( my_state.load(std::memory_order_acquire)==st_init && my_state.compare_exchange_strong( excepted, st_starting ) ) ) {
        // after this point, remove_server_ref() must be done by created thread
#if USE_WINTHREAD
        my_handle = ipc_thread_monitor::launch( thread_routine, this, my_server.my_stack_size, &this->my_index );
#elif USE_PTHREAD
        {
        affinity_helper fpa;
        fpa.protect_affinity_mask( /*restore_process_mask=*/true );
        my_handle = ipc_thread_monitor::launch( thread_routine, this, my_server.my_stack_size );
        if( my_handle == 0 ) {
            runtime_warning( "Unable to create new thread for process %d", getpid() );
            state_t s = st_starting;
            my_state.compare_exchange_strong(s, st_init);
            if (st_starting != s) {
                // Do shutdown during startup. my_handle can't be released
                // by start_shutdown, because my_handle value might be not set yet
                // at time of transition from st_starting to st_quit.
                __TBB_ASSERT( s==st_quit, nullptr );
                release_handle( my_handle, my_server.my_join_workers );
            }
            return false;
        } else {
            my_server.my_ref_count++;
        }
        // Implicit destruction of fpa resets original affinity mask.
        }
#endif /* USE_PTHREAD */
        state_t s = st_starting;
        my_state.compare_exchange_strong(s, st_normal);
        if( st_starting!=s ) {
            // Do shutdown during startup. my_handle can't be released
            // by start_shutdown, because my_handle value might be not set yet
            // at time of transition from st_starting to st_quit.
            __TBB_ASSERT( s==st_quit, nullptr );
            release_handle( my_handle, my_server.my_join_workers );
        }
    }
    else {
        my_thread_monitor.notify();
    }

    return true;
}

//------------------------------------------------------------------------
// Methods of ipc_stopper
//------------------------------------------------------------------------
#if _MSC_VER && !defined(__INTEL_COMPILER)
    // Suppress overzealous compiler warnings about an initialized variable 'sink_for_alloca' not referenced
    #pragma warning(push)
    #pragma warning(disable:4189)
#endif
#if __MINGW32__ && __GNUC__==4 &&__GNUC_MINOR__>=2 && !__MINGW64__
// ensure that stack is properly aligned
__attribute__((force_align_arg_pointer))
#endif
__RML_DECL_THREAD_ROUTINE ipc_stopper::thread_routine(void* arg) {
    ipc_stopper* self = static_cast<ipc_stopper*>(arg);
    AVOID_64K_ALIASING( self->my_index );
    self->run();
    return 0;
}
#if _MSC_VER && !defined(__INTEL_COMPILER)
    #pragma warning(pop)
#endif

void ipc_stopper::run() {
    // Transiting to st_normal here would require setting my_handle,
    // which would create race with the launching thread and
    // complications in handle management on Windows.

    while( my_state.load(std::memory_order_acquire)!=st_quit ) {
        if( my_server.wait_stop_thread() ) {
            if( my_state.load(std::memory_order_acquire)!=st_quit ) {
                if( !my_server.stop_one() ) {
                    my_server.add_stop_thread();
                    tbb::detail::r1::prolonged_pause();
                }
            }
        }
    }

    my_server.remove_server_ref();
}

inline bool ipc_stopper::wake_or_launch() {
    state_t excepted = st_init;
    if( ( my_state.load(std::memory_order_acquire)==st_init && my_state.compare_exchange_strong( excepted, st_starting ) ) ) {
        // after this point, remove_server_ref() must be done by created thread
#if USE_WINTHREAD
        my_handle = ipc_thread_monitor::launch( thread_routine, this, my_server.my_stack_size, &this->my_index );
#elif USE_PTHREAD
        {
        affinity_helper fpa;
        fpa.protect_affinity_mask( /*restore_process_mask=*/true );
        my_handle = ipc_thread_monitor::launch( thread_routine, this, my_server.my_stack_size );
        if( my_handle == 0 ) {
            runtime_warning( "Unable to create new thread for process %d", getpid() );
            state_t s = st_starting;
            my_state.compare_exchange_strong(s, st_init);
            if (st_starting != s) {
                // Do shutdown during startup. my_handle can't be released
                // by start_shutdown, because my_handle value might be not set yet
                // at time of transition from st_starting to st_quit.
                __TBB_ASSERT( s==st_quit, nullptr );
                release_handle( my_handle, my_server.my_join_workers );
            }
            return false;
        } else {
            my_server.my_ref_count++;
        }
        // Implicit destruction of fpa resets original affinity mask.
        }
#endif /* USE_PTHREAD */
        state_t s = st_starting;
        my_state.compare_exchange_strong(s, st_normal);
        if( st_starting!=s ) {
            // Do shutdown during startup. my_handle can't be released
            // by start_shutdown, because my_handle value might be not set yet
            // at time of transition from st_starting to st_quit.
            __TBB_ASSERT( s==st_quit, nullptr );
            release_handle( my_handle, my_server.my_join_workers );
        }
    }
    else {
        my_thread_monitor.notify();
    }

    return true;
}

//------------------------------------------------------------------------
// Methods of ipc_server
//------------------------------------------------------------------------
ipc_server::ipc_server(tbb_client& client) :
    my_client( client ),
    my_stack_size( client.min_stack_size() ),
    my_thread_array(nullptr),
    my_join_workers(false),
    my_waker(nullptr),
    my_stopper(nullptr)
{
    my_ref_count = 1;
    my_slack = 0;
#if TBB_USE_ASSERT
    my_net_slack_requests = 0;
#endif /* TBB_USE_ASSERT */
    my_n_thread = tbb::internal::rml::get_num_threads(IPC_MAX_THREADS_VAR_NAME);
    if( my_n_thread==0 ) {
        my_n_thread = tbb::detail::r1::AvailableHwConcurrency();
        __TBB_ASSERT( my_n_thread>0, nullptr );
    }

    my_asleep_list_root = nullptr;
    my_thread_array = tbb::cache_aligned_allocator<padded_ipc_worker>().allocate( my_n_thread );
    for( size_t i=0; i<my_n_thread; ++i ) {
        ipc_worker* t = new( &my_thread_array[i] ) padded_ipc_worker( *this, client, i );
        t->my_next = my_asleep_list_root;
        my_asleep_list_root = t;
    }

    my_waker = tbb::cache_aligned_allocator<ipc_waker>().allocate(1);
    new( my_waker ) ipc_waker( *this, client, my_n_thread );

    my_stopper = tbb::cache_aligned_allocator<ipc_stopper>().allocate(1);
    new( my_stopper ) ipc_stopper( *this, client, my_n_thread + 1 );

    char* active_sem_name = get_active_sem_name();
    my_active_sem = sem_open( active_sem_name, O_CREAT, IPC_SEM_MODE, my_n_thread - 1 );
    __TBB_ASSERT( my_active_sem, "Unable to open active threads semaphore" );
    delete[] active_sem_name;

    char* stop_sem_name = get_stop_sem_name();
    my_stop_sem = sem_open( stop_sem_name, O_CREAT, IPC_SEM_MODE, 0 );
    __TBB_ASSERT( my_stop_sem, "Unable to open stop threads semaphore" );
    delete[] stop_sem_name;
}

ipc_server::~ipc_server() {
    __TBB_ASSERT( my_net_slack_requests.load(std::memory_order_relaxed)==0, nullptr );

    for( size_t i=my_n_thread; i--; )
        my_thread_array[i].~padded_ipc_worker();
    tbb::cache_aligned_allocator<padded_ipc_worker>().deallocate( my_thread_array, my_n_thread );
    tbb::detail::d0::poison_pointer( my_thread_array );

    my_waker->~ipc_waker();
    tbb::cache_aligned_allocator<ipc_waker>().deallocate( my_waker, 1 );
    tbb::detail::d0::poison_pointer( my_waker );

    my_stopper->~ipc_stopper();
    tbb::cache_aligned_allocator<ipc_stopper>().deallocate( my_stopper, 1 );
    tbb::detail::d0::poison_pointer( my_stopper );

    sem_close( my_active_sem );
    sem_close( my_stop_sem );
}

inline bool ipc_server::try_insert_in_asleep_list(ipc_worker& t) {
    asleep_list_mutex_type::scoped_lock lock;
    if( !lock.try_acquire( my_asleep_list_mutex ) )
        return false;
    // Contribute to slack under lock so that if another takes that unit of slack,
    // it sees us sleeping on the list and wakes us up.
    int k = ++my_slack;
    if( k<=0 ) {
        t.my_next = my_asleep_list_root.load(std::memory_order_relaxed);
        my_asleep_list_root.store(&t, std::memory_order_relaxed);
        return true;
    } else {
        --my_slack;
        return false;
    }
}

inline bool ipc_server::try_insert_in_asleep_list_forced(ipc_worker& t) {
    asleep_list_mutex_type::scoped_lock lock;
    if( !lock.try_acquire( my_asleep_list_mutex ) )
        return false;
    // Contribute to slack under lock so that if another takes that unit of slack,
    // it sees us sleeping on the list and wakes us up.
    ++my_slack;
    t.my_next = my_asleep_list_root.load(std::memory_order_relaxed);
    my_asleep_list_root.store(&t, std::memory_order_relaxed);
    return true;
}

inline bool ipc_server::wait_active_thread() {
    if( sem_wait( my_active_sem ) == 0 ) {
        ++my_global_thread_count;
        return true;
    }
    return false;
}

inline bool ipc_server::try_get_active_thread() {
    if( sem_trywait( my_active_sem ) == 0 ) {
        ++my_global_thread_count;
        return true;
    }
    return false;
}

inline void ipc_server::release_active_thread() {
    release_thread_sem( my_active_sem );
}

inline bool ipc_server::wait_stop_thread() {
    struct timespec ts;
    if( clock_gettime( CLOCK_REALTIME, &ts )==0 ) {
        ts.tv_sec++;
        if( sem_timedwait( my_stop_sem, &ts )==0 ) {
            return true;
        }
    }
    return false;
}

inline void ipc_server::add_stop_thread() {
    sem_post( my_stop_sem );
}

void ipc_server::wake_some( int additional_slack, int active_threads ) {
    __TBB_ASSERT( additional_slack>=0, nullptr );
    ipc_worker* wakee[2];
    ipc_worker **w = wakee;
    {
        asleep_list_mutex_type::scoped_lock lock(my_asleep_list_mutex);
        while( active_threads>0 && my_asleep_list_root.load(std::memory_order_relaxed) && w<wakee+2 ) {
            if( additional_slack>0 ) {
                if( additional_slack+my_slack.load(std::memory_order_acquire)<=0 ) // additional demand does not exceed surplus supply
                    break;
                --additional_slack;
            } else {
                // Chain reaction; Try to claim unit of slack
                int old;
                do {
                    old = my_slack.load(std::memory_order_relaxed);
                    if( old<=0 ) goto done;
                } while( !my_slack.compare_exchange_strong( old, old-1 ) );
            }
            // Pop sleeping worker to combine with claimed unit of slack
            my_asleep_list_root.store(
                (*w++ = my_asleep_list_root.load(std::memory_order_relaxed))->my_next,
                std::memory_order_relaxed
            );
            --active_threads;
        }
        if( additional_slack ) {
            // Contribute our unused slack to my_slack.
            my_slack += additional_slack;
        }
    }
done:
    while( w>wakee ) {
        if( !(*--w)->wake_or_launch() ) {
            add_stop_thread();
            do {
            } while( !try_insert_in_asleep_list_forced(**w) );
            release_active_thread();
        }
    }
    while( active_threads ) {
        release_active_thread();
        --active_threads;
    }
}

void ipc_server::wake_one_forced( int additional_slack ) {
    __TBB_ASSERT( additional_slack>=0, nullptr );
    ipc_worker* wakee[1];
    ipc_worker **w = wakee;
    {
        asleep_list_mutex_type::scoped_lock lock(my_asleep_list_mutex);
        while( my_asleep_list_root.load(std::memory_order_relaxed) && w<wakee+1 ) {
            if( additional_slack>0 ) {
                if( additional_slack+my_slack.load(std::memory_order_acquire)<=0 ) // additional demand does not exceed surplus supply
                    break;
                --additional_slack;
            } else {
                // Chain reaction; Try to claim unit of slack
                int old;
                do {
                    old = my_slack.load(std::memory_order_relaxed);
                    if( old<=0 ) goto done;
                } while( !my_slack.compare_exchange_strong( old, old-1 ) );
            }
            // Pop sleeping worker to combine with claimed unit of slack
            my_asleep_list_root.store(
                (*w++ = my_asleep_list_root.load(std::memory_order_relaxed))->my_next,
                std::memory_order_relaxed);
        }
        if( additional_slack ) {
            // Contribute our unused slack to my_slack.
            my_slack += additional_slack;
        }
    }
done:
    while( w>wakee ) {
        if( !(*--w)->wake_or_launch() ) {
            add_stop_thread();
            do {
            } while( !try_insert_in_asleep_list_forced(**w) );
        }
    }
}

bool ipc_server::stop_one() {
    ipc_worker* current = nullptr;
    ipc_worker* next = nullptr;
    {
        asleep_list_mutex_type::scoped_lock lock(my_asleep_list_mutex);
        if( my_asleep_list_root.load(std::memory_order_relaxed) ) {
            current = my_asleep_list_root.load(std::memory_order_relaxed);
            if( current->my_state.load(std::memory_order_relaxed)==ipc_worker::st_normal ) {
                next = current->my_next;
                while( next!= nullptr && next->my_state.load(std::memory_order_relaxed)==ipc_worker::st_normal ) {
                    current = next;
                    next = current->my_next;
                }
                current->start_stopping( my_join_workers );
                return true;
            }
        }
    }
    return false;
}

void ipc_server::adjust_job_count_estimate( int delta ) {
#if TBB_USE_ASSERT
    my_net_slack_requests+=delta;
#endif /* TBB_USE_ASSERT */
    if( my_n_thread > 1 ) {
        if( delta<0 ) {
            my_slack+=delta;
        } else if( delta>0 ) {
            int active_threads = 0;
            if( try_get_active_thread() ) {
                ++active_threads;
                if( try_get_active_thread() ) {
                    ++active_threads;
                }
            }
            wake_some( delta, active_threads );

            if( !my_waker->wake_or_launch() ) {
                add_stop_thread();
            }
            if( !my_stopper->wake_or_launch() ) {
                add_stop_thread();
            }
        }
    } else { // Corner case when RML shouldn't provide any worker thread but client has to have at least one
        if( delta<0 ) {
            my_slack += delta;
        } else {
            wake_one_forced( delta );
        }
    }
}

//------------------------------------------------------------------------
// RML factory methods
//------------------------------------------------------------------------

#if USE_PTHREAD

static tbb_client* my_global_client = nullptr;
static tbb_server* my_global_server = nullptr;

void rml_atexit() {
    release_resources();
}

void rml_atfork_child() {
    if( my_global_server!=nullptr && my_global_client!=nullptr ) {
        ipc_server* server = static_cast<ipc_server*>( my_global_server );
        server->~ipc_server();
        // memset( server, 0, sizeof(ipc_server) );
        new( server ) ipc_server( *my_global_client );
        pthread_atfork( nullptr, nullptr, rml_atfork_child );
        atexit( rml_atexit );
    }
}

#endif /* USE_PTHREAD */

extern "C" tbb_factory::status_type __TBB_make_rml_server(tbb_factory& /*f*/, tbb_server*& server, tbb_client& client) {
    server = new( tbb::cache_aligned_allocator<ipc_server>().allocate(1) ) ipc_server(client);
#if USE_PTHREAD
    my_global_client = &client;
    my_global_server = server;
    pthread_atfork( nullptr, nullptr, rml_atfork_child );
    atexit( rml_atexit );
#endif /* USE_PTHREAD */
    if( getenv( "RML_DEBUG" ) ) {
        runtime_warning("IPC server is started");
    }
    return tbb_factory::st_success;
}

extern "C" void __TBB_call_with_my_server_info(::rml::server_info_callback_t /*cb*/, void* /*arg*/) {
}

} // namespace rml
} // namespace detail

} // namespace tbb