Pthread pause based on pthread user data
[mirrors/Programs.git] / c / pthread_extra / pthread_pause.c
1 #define __PTHREAD_EXTRA_INTERNAL
2
3 #include <pthread.h>
4 #include <pthread_extra.h>
5 #include <signal.h>
6 #include <errno.h>
7 #include <unistd.h>
8 #include <sys/resource.h>
9 //#include <stdio.h>
10 //#include <sys/time.h>
11
12 void pthread_pause_handler() {
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
19 sigset_t sigset;
20 sigfillset(&sigset);
21 sigdelset(&sigset, PTHREAD_XSIG_STOP);
22 while(!pthread_user_data_internal(pthread_self())->running) {
23 sigsuspend(&sigset);
24 }
25 }
26
27 void pthread_pause_enable() {
28 //Nesting signals too deep is not good for stack
29 //You can get runtime stats using following command:
30 //grep -i sig /proc/$(pgrep binary)/status
31 struct rlimit sigq = {.rlim_cur = 32, .rlim_max=32};
32 setrlimit(RLIMIT_SIGPENDING, &sigq);
33
34 //Setup signal handler
35 signal(PTHREAD_XSIG_STOP, pthread_pause_handler);
36
37 //Unblock signal
38 sigset_t sigset;
39 sigemptyset(&sigset);
40 sigaddset(&sigset, PTHREAD_XSIG_STOP);
41 pthread_sigmask(SIG_UNBLOCK, &sigset, NULL);
42 }
43
44 void pthread_pause_disable() {
45 //Block signal
46 sigset_t sigset;
47 sigemptyset(&sigset);
48 sigaddset(&sigset, PTHREAD_XSIG_STOP);
49 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
50 }
51
52 int pthread_pause(pthread_t thread) {
53 //Set thread as paused and notify it via signal (wait when queue full)
54 pthread_user_data_internal(thread)->running = 0;
55 while(pthread_kill(thread, PTHREAD_XSIG_STOP) == EAGAIN) usleep(1000);
56 return 0;
57 }
58
59 int pthread_unpause(pthread_t thread) {
60 //Set thread as running and notify it via signal (wait when queue full)
61 pthread_user_data_internal(thread)->running = 1;
62 while(pthread_kill(thread, PTHREAD_XSIG_STOP) == EAGAIN) usleep(1000);
63 return 0;
64 }
This page took 0.374458 seconds and 4 git commands to generate.