Make terminate_threads() less likely to leave _threads containing invalid pointers.
[dcpomatic.git] / src / lib / server.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "server.h"
22 #include "dcpomatic_socket.h"
23
24 #include "i18n.h"
25
26 using boost::shared_ptr;
27
28 Server::Server (int port, int timeout)
29         : _terminate (false)
30         , _acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port))
31         , _timeout (timeout)
32 {
33
34 }
35
36 Server::~Server ()
37 {
38         {
39                 boost::mutex::scoped_lock lm (_mutex);
40                 _terminate = true;
41         }
42
43         _acceptor.close ();
44         stop ();
45 }
46
47 void
48 Server::run ()
49 {
50         start_accept ();
51         _io_service.run ();
52 }
53
54 void
55 Server::start_accept ()
56 {
57         {
58                 boost::mutex::scoped_lock lm (_mutex);
59                 if (_terminate) {
60                         return;
61                 }
62         }
63
64         shared_ptr<Socket> socket (new Socket(_timeout));
65         _acceptor.async_accept (socket->socket (), boost::bind (&Server::handle_accept, this, socket, boost::asio::placeholders::error));
66 }
67
68 void
69 Server::handle_accept (shared_ptr<Socket> socket, boost::system::error_code const & error)
70 {
71         if (error) {
72                 return;
73         }
74
75         handle (socket);
76         start_accept ();
77 }
78
79 void
80 Server::stop ()
81 {
82         _io_service.stop ();
83 }