Commit | Line | Data |
---|---|---|
88342701 TM |
1 | #define __PTHREAD_EXTRA_INTERNAL |
2 | ||
a8e71e8f TM |
3 | #include <pthread.h> |
4 | #include <pthread_extra.h> | |
5 | #include <signal.h> | |
88342701 TM |
6 | #include <errno.h> |
7 | #include <unistd.h> | |
8 | #include <sys/resource.h> | |
9 | //#include <stdio.h> | |
10 | //#include <sys/time.h> | |
a8e71e8f TM |
11 | |
12 | void pthread_pause_handler() { | |
88342701 TM |
13 | //Do nothing when there are more signals pending (to cleanup the queue) |
14 | sigset_t pending; | |
15 | sigpending(&pending); | |
16 | if(sigismember(&pending, PTHREAD_XSIG_STOP)) return; | |
17 | ||
18 | //Keep waiting for signals until we are supposed to be running | |
a8e71e8f TM |
19 | sigset_t sigset; |
20 | sigfillset(&sigset); | |
88342701 | 21 | sigdelset(&sigset, PTHREAD_XSIG_STOP); |
24286ba9 | 22 | if(!pthread_user_data_internal(pthread_self())->running) { |
88342701 TM |
23 | sigsuspend(&sigset); |
24 | } | |
a8e71e8f TM |
25 | } |
26 | ||
27 | void pthread_pause_enable() { | |
ee099ba7 TM |
28 | //Add thread to internal registry |
29 | pthread_user_data_internal(pthread_self()); | |
30 | ||
88342701 TM |
31 | //Nesting signals too deep is not good for stack |
32 | //You can get runtime stats using following command: | |
33 | //grep -i sig /proc/$(pgrep binary)/status | |
34 | struct rlimit sigq = {.rlim_cur = 32, .rlim_max=32}; | |
35 | setrlimit(RLIMIT_SIGPENDING, &sigq); | |
36 | ||
37 | //Setup signal handler | |
a8e71e8f | 38 | signal(PTHREAD_XSIG_STOP, pthread_pause_handler); |
88342701 TM |
39 | |
40 | //Unblock signal | |
41 | sigset_t sigset; | |
42 | sigemptyset(&sigset); | |
43 | sigaddset(&sigset, PTHREAD_XSIG_STOP); | |
44 | pthread_sigmask(SIG_UNBLOCK, &sigset, NULL); | |
45 | } | |
46 | ||
47 | void pthread_pause_disable() { | |
ee099ba7 TM |
48 | //Add thread to internal registry |
49 | pthread_user_data_internal(pthread_self()); | |
50 | ||
88342701 TM |
51 | //Block signal |
52 | sigset_t sigset; | |
53 | sigemptyset(&sigset); | |
54 | sigaddset(&sigset, PTHREAD_XSIG_STOP); | |
55 | pthread_sigmask(SIG_BLOCK, &sigset, NULL); | |
56 | } | |
57 | ||
58 | int pthread_pause(pthread_t thread) { | |
59 | //Set thread as paused and notify it via signal (wait when queue full) | |
60 | pthread_user_data_internal(thread)->running = 0; | |
61 | while(pthread_kill(thread, PTHREAD_XSIG_STOP) == EAGAIN) usleep(1000); | |
62 | return 0; | |
63 | } | |
64 | ||
65 | int pthread_unpause(pthread_t thread) { | |
66 | //Set thread as running and notify it via signal (wait when queue full) | |
67 | pthread_user_data_internal(thread)->running = 1; | |
68 | while(pthread_kill(thread, PTHREAD_XSIG_STOP) == EAGAIN) usleep(1000); | |
69 | return 0; | |
a8e71e8f | 70 | } |