experimental session-save speedup
[ardour.git] / libs / pbd / crossthread.posix.cc
1 #include <poll.h>
2
3 CrossThreadChannel::CrossThreadChannel (bool non_blocking)
4         : receive_channel (0)
5         , receive_source (0)
6 {
7         fds[0] = -1;
8         fds[1] = -1;
9
10         if (pipe (fds)) {
11                 error << "cannot create x-thread pipe for read (%2)" << ::strerror (errno) << endmsg;
12                 return;
13         }
14
15         if (non_blocking) {
16                 if (fcntl (fds[0], F_SETFL, O_NONBLOCK)) {
17                         error << "cannot set non-blocking mode for x-thread pipe (read) (" << ::strerror (errno) << ')' << endmsg;
18                         return;
19                 }
20
21                 if (fcntl (fds[1], F_SETFL, O_NONBLOCK)) {
22                         error << "cannot set non-blocking mode for x-thread pipe (write) (%2)" << ::strerror (errno) << ')' << endmsg;
23                         return;
24                 }
25         }
26
27         receive_channel = g_io_channel_unix_new (fds[0]);
28 }
29
30 CrossThreadChannel::~CrossThreadChannel ()
31 {
32         if (receive_source) {
33                 g_source_destroy (receive_source);
34                 receive_source = 0;
35         }
36
37         if (receive_channel) {
38                 g_io_channel_unref (receive_channel);
39                 receive_channel = 0;
40         }
41
42         if (fds[0] >= 0) {
43                 close (fds[0]);
44                 fds[0] = -1;
45         }
46
47         if (fds[1] >= 0) {
48                 close (fds[1]);
49                 fds[1] = -1;
50         }
51 }
52
53 void
54 CrossThreadChannel::wakeup ()
55 {
56         char c = 0;
57         (void) ::write (fds[1], &c, 1);
58 }
59
60 void
61 CrossThreadChannel::drain ()
62 {
63         char buf[64];
64         while (::read (fds[0], buf, sizeof (buf)) > 0) {};
65 }
66
67 int
68 CrossThreadChannel::deliver (char msg)
69 {
70         return ::write (fds[1], &msg, 1);
71 }
72
73 bool
74 CrossThreadChannel::poll_for_request()
75 {
76         struct pollfd pfd[1];
77         pfd[0].fd = fds[0];
78         pfd[0].events = POLLIN|POLLERR|POLLHUP;
79         while(true) {
80                 if (poll (pfd, 1, -1) < 0) {
81                         if (errno == EINTR) {
82                                 continue;
83                         }
84                         break;
85                 }
86                 if (pfd[0].revents & ~POLLIN) {
87                         break;
88                 }
89
90                 if (pfd[0].revents & POLLIN) {
91                         return true;
92                 }
93         }
94         return false;
95 }
96
97 int
98 CrossThreadChannel::receive (char& msg, bool wait)
99 {
100         if (wait) {
101                 if (!poll_for_request ()) {
102                         return -1;
103                 }
104         }
105         return ::read (fds[0], &msg, 1);
106 }