1 /* Copyright 2017-2021 PaGMO development team
2 
3 This file is part of the PaGMO library.
4 
5 The PaGMO library is free software; you can redistribute it and/or modify
6 it under the terms of either:
7 
8   * the GNU Lesser General Public License as published by the Free
9     Software Foundation; either version 3 of the License, or (at your
10     option) any later version.
11 
12 or
13 
14   * the GNU General Public License as published by the Free Software
15     Foundation; either version 3 of the License, or (at your option) any
16     later version.
17 
18 or both in parallel, as here.
19 
20 The PaGMO library is distributed in the hope that it will be useful, but
21 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
22 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
23 for more details.
24 
25 You should have received copies of the GNU General Public License and the
26 GNU Lesser General Public License along with the PaGMO library.  If not,
27 see https://www.gnu.org/licenses/. */
28 
29 #ifndef PAGMO_ISLANDS_FORK_ISLAND_HPP
30 #define PAGMO_ISLANDS_FORK_ISLAND_HPP
31 
32 #include <pagmo/config.hpp>
33 
34 #if defined(PAGMO_WITH_FORK_ISLAND)
35 
36 #include <atomic>
37 #include <string>
38 
39 #include <unistd.h>
40 
41 #include <pagmo/detail/visibility.hpp>
42 #include <pagmo/island.hpp>
43 #include <pagmo/s11n.hpp>
44 
45 namespace pagmo
46 {
47 
48 // Fork island: will offload the evolution to a child process created with the fork() system call.
49 class PAGMO_DLL_PUBLIC fork_island
50 {
51 public:
52     // NOTE: we need to implement these because of the m_pid member,
53     // which has a trivial def ctor and which is missing the copy/move ctors.
54     // m_pid is only informational and it is relevant only while the evolution
55     // is undergoing, we will not copy it or serialize it.
fork_island()56     fork_island() : m_pid(0) {}
fork_island(const fork_island &)57     fork_island(const fork_island &) : fork_island() {}
fork_island(fork_island &&)58     fork_island(fork_island &&) : fork_island() {}
59     void run_evolve(island &) const;
get_name() const60     std::string get_name() const
61     {
62         return "Fork island";
63     }
64     std::string get_extra_info() const;
65     // Get the PID of the child.
get_child_pid() const66     pid_t get_child_pid() const
67     {
68         return m_pid.load();
69     }
70 
71 private:
72     // Object serialization
73     friend class boost::serialization::access;
74     template <typename Archive>
75     void serialize(Archive &, unsigned);
76 
77     mutable std::atomic<pid_t> m_pid;
78 };
79 
80 } // namespace pagmo
81 
82 PAGMO_S11N_ISLAND_EXPORT_KEY(pagmo::fork_island)
83 
84 #else
85 
86 #error The fork_island.hpp header was included, but the fork island is not available on the current platform
87 
88 #endif
89 
90 #endif
91