Fixed deadlocks in pthread_pause
[mirrors/Programs.git] / c / pthread_extra / pthread_pause.c
CommitLineData
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
12void 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
27void pthread_pause_enable() {
88342701
TM
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
a8e71e8f 35 signal(PTHREAD_XSIG_STOP, pthread_pause_handler);
88342701
TM
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
44void 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
52int 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
59int 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;
a8e71e8f 64}
This page took 0.165631 seconds and 4 git commands to generate.