-
Notifications
You must be signed in to change notification settings - Fork 161
/
island.cpp
1081 lines (921 loc) · 39.8 KB
/
island.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2017-2021 PaGMO development team
This file is part of the PaGMO library.
The PaGMO library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any
later version.
or both in parallel, as here.
The PaGMO library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the PaGMO library. If not,
see https://www.gnu.org/licenses/. */
#include <pagmo/config.hpp>
#include <cassert>
#include <chrono>
#include <exception>
#include <future>
#include <initializer_list>
#include <iostream>
#include <memory>
#include <mutex>
#include <optional>
#include <random>
#include <stdexcept>
#include <string>
#include <tuple>
#include <typeindex>
#include <unordered_map>
#include <utility>
#include <vector>
#if defined(PAGMO_HAVE_PTHREAD_ATFORK)
#include <pthread.h>
#endif
#include <boost/any.hpp>
#include <tbb/concurrent_queue.h>
#include <pagmo/algorithm.hpp>
#include <pagmo/archipelago.hpp>
#include <pagmo/detail/gte_getter.hpp>
#include <pagmo/detail/type_name.hpp>
#include <pagmo/exceptions.hpp>
#include <pagmo/io.hpp>
#include <pagmo/island.hpp>
#include <pagmo/islands/thread_island.hpp>
#include <pagmo/population.hpp>
#include <pagmo/r_policy.hpp>
#include <pagmo/rng.hpp>
#include <pagmo/s_policy.hpp>
#include <pagmo/threading.hpp>
#include <pagmo/types.hpp>
#if defined(PAGMO_WITH_FORK_ISLAND)
#include <pagmo/islands/fork_island.hpp>
#endif
// MINGW-specific warnings.
#if defined(__GNUC__) && defined(__MINGW32__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsuggest-attribute=pure"
#endif
namespace pagmo
{
namespace detail
{
namespace
{
// This will contain the time point at which
// the pagmo library is loaded. It is used in the migration
// logging to record the migration time.
const auto initial_timestamp = std::chrono::steady_clock::now();
// Small helper to determine if a future holds an exception.
// The noexcept reasoning is the same as above. Here we could fail
// because of memory errors, but there's not much we can do in such
// a case.
bool future_has_exception(std::future<void> &f) noexcept
{
assert(f.valid());
// Try to get the error.
try {
f.get();
} catch (...) {
// An error was generated. Re-store the exception into the future
// and return true.
// http://en.cppreference.com/w/cpp/experimental/make_exceptional_future
std::promise<void> p;
p.set_exception(std::current_exception());
f = p.get_future();
return true;
}
// No error was raised. Need to reconstruct f to a valid state.
std::promise<void> p;
p.set_value();
f = p.get_future();
return false;
}
// NOTE: this is just a simple wrapper to force noexcept behaviour on std::future::wait().
// If f.wait() throws something, the program will terminate. A valid std::future should not
// throw, but technically the standard does not guarantee that. Having this noexcept wrapper
// simplifies reasoning about exception behaviour in wait(), wait_check(), etc.
void wait_f(const std::future<void> &f) noexcept
{
assert(f.valid());
f.wait();
}
// Small helper to check if a future is still running.
bool future_running(const std::future<void> &f)
{
assert(f.valid());
return f.wait_for(std::chrono::duration<int>::zero()) != std::future_status::ready;
}
} // namespace
} // namespace detail
namespace detail
{
namespace
{
boost::any default_wait_raii_getter()
{
return boost::any{};
}
} // namespace
// NOTE: the default implementation just returns a defected boost::any, whose ctor and dtor
// will have no effect.
std::function<boost::any()> wait_raii_getter = &default_wait_raii_getter;
namespace
{
// This is the default UDI type selector. It will select the thread_island if both algorithm
// and population provide at least the basic thread safety guarantee. Otherwise, it will select
// the fork_island, if available.
void default_island_factory(const algorithm &algo, const population &pop, std::unique_ptr<detail::isl_inner_base> &ptr)
{
(void)algo;
(void)pop;
#if defined(PAGMO_WITH_FORK_ISLAND)
if (algo.get_thread_safety() < thread_safety::basic
|| pop.get_problem().get_thread_safety() < thread_safety::basic) {
ptr = std::make_unique<isl_inner<fork_island>>();
return;
}
#endif
ptr = std::make_unique<isl_inner<thread_island>>();
}
} // namespace
// Static init.
std::function<void(const algorithm &, const population &, std::unique_ptr<detail::isl_inner_base> &)> island_factory
= &default_island_factory;
namespace
{
// Factory function for the global task_queue cache. Note that the cache is returned
// wrapped in a unique_ptr, so that we can reset it while avoiding calling its
// destructor in the child process after a fork().
auto &get_task_queue_cache()
{
static auto tq_cache = std::make_unique<tbb::concurrent_queue<std::unique_ptr<task_queue>>>();
return tq_cache;
}
#if defined(PAGMO_HAVE_PTHREAD_ATFORK)
// NOTE: this machinery is used to automatically clean up the task queue cache in the child
// process after a fork(). This is necessary because fork() duplicates the memory state of the calling
// thread only, and the destruction of the other thread objects in the task queue cache leads to deadlocks.
// In order to accomplish this, we register a callback via pthread_atfork() that will be called
// by the child process immediately after fork(). The registration of the callback needs to be done
// once per thread, hence we use a thread local std::once_flag in conjuction with the std::call_once()
// mechanism.
// Per-thread flag to indicate that the fork() callback has been registered.
thread_local std::once_flag fork_callback_flag;
// The callback that will be invoked by the child process after fork().
extern "C" void clear_task_queue_cache() noexcept
{
// NOTE: there are no concerns about thread-safety in the modification
// of the global cache: in the child process there is only 1 running thread.
auto &tqc_ptr = get_task_queue_cache();
// Release the pointer to the current cache, in order to avoid invoking its
// destructor which would lead to a deadlock.
[[maybe_unused]] auto old_ptr = tqc_ptr.release();
// Create a new empty cache.
tqc_ptr = std::make_unique<tbb::concurrent_queue<std::unique_ptr<task_queue>>>();
}
#endif
} // namespace
// Helper to either fetch a task_queue from a global cache,
// or to create a new one (in case the global cache is empty).
std::unique_ptr<task_queue> get_task_queue()
{
// Fetch the global cache.
auto &tqc = get_task_queue_cache();
assert(static_cast<bool>(tqc));
#if defined(PAGMO_HAVE_PTHREAD_ATFORK)
// Register the fork() callback here, after
// having triggered the construction of the global cache.
std::call_once(fork_callback_flag, []() { ::pthread_atfork(nullptr, nullptr, clear_task_queue_cache); });
#endif
// Try to pop a task queue from the cache,
// or create a new one.
std::unique_ptr<task_queue> retval;
if (!tqc->try_pop(retval)) {
retval = std::make_unique<task_queue>();
}
return retval;
}
// NOTE: thread_island is ok as default choice, as the null_prob/null_algo
// are both thread safe.
island_data::island_data()
: isl_ptr(std::make_unique<isl_inner<thread_island>>()), algo(std::make_shared<algorithm>()),
pop(std::make_shared<population>())
{
}
// This is used only in the copy ctor of island. The island will come from the clone()
// method of an isl_inner, the algo/pop from the island's getters. The r_policy
// will come directly from the island's data member, as the r_policy is supposed
// to be thread-safe.
island_data::island_data(std::unique_ptr<isl_inner_base> &&ptr, algorithm &&a, population &&p, const r_policy &r,
const s_policy &s)
: isl_ptr(std::move(ptr)), algo(std::make_shared<algorithm>(std::move(a))),
pop(std::make_shared<population>(std::move(p))), r_pol(r), s_pol(s)
{
}
island_data::~island_data()
{
// Consume all tasks in the queue.
queue->wait_all();
// Move the queue to the cache.
get_task_queue_cache()->push(std::move(queue));
}
namespace
{
// A map to link a human-readable description to evolve_status.
const std::unordered_map<evolve_status, std::string> island_statuses
= {{evolve_status::idle, "idle"},
{evolve_status::busy, "busy"},
{evolve_status::idle_error, "idle - **error occurred**"},
{evolve_status::busy_error, "busy - **error occurred**"}};
} // namespace
} // namespace detail
#if !defined(PAGMO_DOXYGEN_INVOKED)
// Provide the stream operator overload for evolve_status.
std::ostream &operator<<(std::ostream &os, evolve_status es)
{
return os << detail::island_statuses.at(es);
}
#endif
// NOTE: the idea in the move members and the dtor is that
// we want to wait *and* erase any future in the island, before doing
// the move/destruction. Thus we use this small wrapper.
void island::wait_check_ignore()
{
try {
wait_check();
// LCOV_EXCL_START
} catch (...) {
}
// LCOV_EXCL_STOP
}
/// Default constructor.
/**
*\verbatim embed:rst:leading-asterisk
* The default constructor will initialise an island containing a UDI of type :cpp:class:`~pagmo::thread_island`,
* and default-constructed algorithm, population and replacement/selection policies.
* \endverbatim
*
* @throws unspecified any exception thrown by any invoked constructor or by memory allocation failures.
*/
island::island() : m_ptr(std::make_unique<idata_t>()) {}
/// Copy constructor.
/**
* The copy constructor will initialise an island containing a copy of <tt>other</tt>'s UDI, population,
* algorithm and replacement/selection policies. It is safe to call this constructor while \p other is evolving.
*
* @param other the island tht will be copied.
*
* @throws unspecified any exception thrown by:
* - get_population() and get_algorithm(),
* - memory allocation errors,
* - copying the island's members.
*/
island::island(const island &other)
: m_ptr(std::make_unique<idata_t>(other.m_ptr->isl_ptr->clone(), other.get_algorithm(), other.get_population(),
other.m_ptr->r_pol, other.m_ptr->s_pol))
{
// NOTE: the idata_t ctor will set the archi ptr to null. The archi ptr is never copied.
assert(m_ptr->archi_ptr == nullptr);
}
/// Move constructor.
/**
* The move constructor will transfer the state of \p other into \p this, after any ongoing
* evolution in \p other is finished.
*
* @param other the island that will be moved.
*/
island::island(island &&other) noexcept
{
other.wait_check_ignore();
m_ptr = std::move(other.m_ptr);
}
/// Destructor.
/**
* If the island has not been moved-from, the destructor will call island::wait_check(),
* ignoring any exception that might be thrown.
*/
island::~island()
{
// If the island has been moved from, don't do anything.
if (m_ptr) {
wait_check_ignore();
}
}
/// Move assignment.
/**
* Move assignment will transfer the state of \p other into \p this, after any ongoing
* evolution in \p this and \p other is finished.
*
* @param other the island tht will be moved.
*
* @return a reference to \p this.
*/
island &island::operator=(island &&other) noexcept
{
if (this != &other) {
if (m_ptr) {
wait_check_ignore();
}
other.wait_check_ignore();
m_ptr = std::move(other.m_ptr);
}
return *this;
}
/// Copy assignment.
/**
* Copy assignment is implemented as copy construction followed by move assignment.
*
* @param other the island tht will be copied.
*
* @return a reference to \p this.
*
* @throws unspecified any exception thrown by the copy constructor.
*/
island &island::operator=(const island &other)
{
if (this != &other) {
*this = island(other);
}
return *this;
}
void island::evolve(unsigned n)
{
// First add an empty future, so that if an exception is thrown
// we will not have modified m_futures, nor we will have a future
// in flight which we cannot wait upon.
m_ptr->futures.emplace_back();
try {
// Move assign a new future provided by the enqueue() method.
// NOTE: enqueue either returns a valid future, or throws without
// having enqueued any task.
m_ptr->futures.back() = m_ptr->queue->enqueue([this, n]() {
// Random engine for use in the migration logic.
// Wrap it in an optional so that, if we don't need
// it, we don't waste CPU/memory.
std::optional<std::mt19937> migr_eng;
// Cache the archi pointer.
const auto aptr = this->m_ptr->archi_ptr;
// Figure out what is the island's index in the archi, if we are
// in an archi. Otherwise, this variable will be unused.
const auto isl_idx = aptr ? aptr->get_island_idx(*this) : 0u;
for (auto i = 0u; i < n; ++i) {
if (aptr) {
// If the island is in an archi, before
// launching the evolution migrate the
// individuals from the connecting islands.
// Get the indices of the islands with a connection
// towards this.
// NOTE: the get_island_connections() helper will take care
// of converting topology indices to island indices.
const auto connections = aptr->get_island_connections(isl_idx);
assert(connections.first.size() == connections.second.size());
// Do something only if we actually have connections.
if (connections.first.size()) {
// Init the rng engine, if necessary.
if (!migr_eng) {
migr_eng.emplace(static_cast<std::mt19937::result_type>(random_device::next()));
}
// Fetch the migration type and the migrant handling policy
// from the archipelago.
const auto mt = aptr->get_migration_type();
const auto mh = aptr->get_migrant_handling();
// Small helper to turn a group of individuals into
// an ID -> (dv, fv) map. inds will be destroyed
// in the process.
using inds_map_t
= std::unordered_map<unsigned long long, std::pair<vector_double, vector_double>>;
auto group_to_map = [](individuals_group_t &&inds) -> inds_map_t {
inds_map_t retval;
for (decltype(std::get<0>(inds).size()) j = 0; j < std::get<0>(inds).size(); ++j) {
retval[std::get<0>(inds)[j]]
= std::make_pair(std::move(std::get<1>(inds)[j]), std::move(std::get<2>(inds)[j]));
}
return retval;
};
if (mt == migration_type::p2p) {
// Point-to-point migration.
// Pick a random island among the islands connecting to this.
const auto conn_idx = std::uniform_int_distribution<decltype(connections.first.size())>(
0, connections.first.size() - 1u)(*migr_eng);
// Throw the dice against the migration probability.
if (std::uniform_real_distribution<>{}(*migr_eng) < connections.second[conn_idx]) {
// Get the source island's index.
const auto src_idx = connections.first[conn_idx];
// Extract or copy the candidate migrants from the archipelago.
const auto migrants = (mh == migrant_handling::preserve)
? aptr->get_migrants(src_idx)
: aptr->extract_migrants(src_idx);
// Extract the migration data from this island.
const auto mig_data = this->get_migration_data();
// Run the replacement policy.
auto new_inds = this->m_ptr->r_pol.replace(std::get<0>(mig_data), std::get<1>(mig_data),
std::get<2>(mig_data), std::get<3>(mig_data),
std::get<4>(mig_data), std::get<5>(mig_data),
std::get<6>(mig_data), migrants);
// Set the new individuals.
this->set_individuals(new_inds);
// Compute the migration timestamp.
const std::chrono::duration<double> mig_ts
= std::chrono::steady_clock::now() - detail::initial_timestamp;
// Turn new_inds into an ID -> (dv, fv) map in order to build the log.
const auto new_inds_map = group_to_map(std::move(new_inds));
// Build the migration log.
archipelago::migration_log_t mlog;
for (auto mig_ID : std::get<0>(migrants)) {
const auto it = new_inds_map.find(mig_ID);
if (it != new_inds_map.end()) {
mlog.emplace_back(mig_ts.count(), mig_ID, it->second.first, it->second.second,
src_idx, isl_idx);
}
}
// Append it.
aptr->append_migration_log(mlog);
}
} else {
// Broadcast migration.
// Group of candidate migrants from the all
// the islands connecting to this.
// We will build this below iteratively.
individuals_group_t migrants;
// Vector to pair source island indices to the corresponding
// candidate migrants. This will contain the same set of individuals
// as migrants, but split according to the source island. This is needed
// to build the migration log.
std::vector<std::pair<archipelago::size_type, individuals_group_t>> split_migrants;
for (decltype(connections.first.size()) j = 0; j < connections.first.size(); ++j) {
// Throw the dice against the migration probability.
if (std::uniform_real_distribution<>{}(*migr_eng) < connections.second[j]) {
// Get the source island's index.
const auto src_idx = connections.first[j];
// Extract or copy the candidate migrants from the archipelago.
auto cur_migrants = (mh == migrant_handling::preserve)
? aptr->get_migrants(src_idx)
: aptr->extract_migrants(src_idx);
// Add them to the global migrants vector.
std::get<0>(migrants).insert(std::get<0>(migrants).end(),
std::get<0>(cur_migrants).begin(),
std::get<0>(cur_migrants).end());
std::get<1>(migrants).insert(std::get<1>(migrants).end(),
std::get<1>(cur_migrants).begin(),
std::get<1>(cur_migrants).end());
std::get<2>(migrants).insert(std::get<2>(migrants).end(),
std::get<2>(cur_migrants).begin(),
std::get<2>(cur_migrants).end());
// Add them to split_migrants too.
split_migrants.emplace_back(src_idx, std::move(cur_migrants));
}
}
// Extract the migration data from this island.
const auto mig_data = this->get_migration_data();
// Run the replacement policy.
auto new_inds = this->m_ptr->r_pol.replace(std::get<0>(mig_data), std::get<1>(mig_data),
std::get<2>(mig_data), std::get<3>(mig_data),
std::get<4>(mig_data), std::get<5>(mig_data),
std::get<6>(mig_data), migrants);
// Set the new individuals.
this->set_individuals(new_inds);
// Compute the migration timestamp.
const std::chrono::duration<double> mig_ts
= std::chrono::steady_clock::now() - detail::initial_timestamp;
// Turn new_inds into an ID -> (dv, fv) map in order to build the log.
const auto new_inds_map = group_to_map(std::move(new_inds));
// Build the migration log.
archipelago::migration_log_t mlog;
for (const auto &p : split_migrants) {
const auto src_idx = p.first;
for (auto mig_ID : std::get<0>(p.second)) {
const auto it = new_inds_map.find(mig_ID);
if (it != new_inds_map.end()) {
mlog.emplace_back(mig_ts.count(), mig_ID, it->second.first, it->second.second,
src_idx, isl_idx);
}
}
}
// Append it.
aptr->append_migration_log(mlog);
}
}
}
// Run the evolution.
this->m_ptr->isl_ptr->run_evolve(*this);
if (aptr) {
// If the island is in an archi, after evolution select
// the migrating individuals and place them in the archi's migrants
// database.
// Extract the migration data from this island.
const auto mig_data = this->get_migration_data();
// Select the individuals to place into the archi's
// migration database.
auto mig_inds = this->m_ptr->s_pol.select(
std::get<0>(mig_data), std::get<1>(mig_data), std::get<2>(mig_data), std::get<3>(mig_data),
std::get<4>(mig_data), std::get<5>(mig_data), std::get<6>(mig_data));
// Place them in the database.
aptr->set_migrants(isl_idx, std::move(mig_inds));
}
}
});
// LCOV_EXCL_START
} catch (...) {
// We end up here only if enqueue threw. In such a case, we need to cleanup
// the empty future we added above before re-throwing and exiting.
m_ptr->futures.pop_back();
throw;
// LCOV_EXCL_STOP
}
}
/// Block until evolution ends and re-raise the first stored exception.
/**
* This method will block until all the evolution tasks enqueued via island::evolve() have been completed.
* If one task enqueued after the last call to wait_check() threw an exception, the exception will be re-thrown
* by this method. If more than one task enqueued after the last call to wait_check() threw an exception,
* this method will re-throw the exception raised by the first enqueued task that threw, and the exceptions
* from all the other tasks that threw will be ignored.
*
* Note that wait_check() resets the status of the island: after a call to wait_check(), status() will always
* return evolve_status::idle.
*
* @throws unspecified any exception thrown by evolution tasks.
*/
void island::wait_check()
{
auto iwr = detail::wait_raii_getter();
(void)iwr;
for (auto it = m_ptr->futures.begin(); it != m_ptr->futures.end(); ++it) {
assert(it->valid());
try {
it->get();
} catch (...) {
// If any of the futures stores an exception, we will re-raise it.
// But first, we need to get all the other futures and erase the futures
// vector.
// NOTE: everything is this block is noexcept.
for (it = it + 1; it != m_ptr->futures.end(); ++it) {
detail::wait_f(*it);
}
m_ptr->futures.clear();
throw;
}
}
m_ptr->futures.clear();
}
/// Block until evolution ends.
/**
* This method will block until all the evolution tasks enqueued via island::evolve() have been completed.
* Exceptions thrown by the enqueued tasks can be re-raised via wait_check(): they will **not** be re-thrown
* by this method. Also, contrary to wait_check(), this method will **not** reset the status of the island:
* after a call to wait(), status() will always return either evolve_status::idle or evolve_status::idle_error.
*/
void island::wait()
{
// NOTE: we use this function in move ops and in the dtor, which are all noexcept. In theory we could
// end up aborting in case the wait_raii mechanism throws in such cases. We could also end up aborting
// due to memory failures in future_has_exception().
// NOTE: the idea here is that, after a wait() call, all the futures of successful tasks have been erased,
// with at most 1 surviving future from the first throwing task. This way, wait() does some cleaning up
// behind the scenes, without changing the behaviour of successive wait_check() and status() calls: wait_check()
// will still re-throw the first exception, and status() will still return idle_error.
auto iwr = detail::wait_raii_getter();
(void)iwr;
const auto it_f = m_ptr->futures.end();
auto it_first_exc = it_f;
for (auto it = m_ptr->futures.begin(); it != it_f; ++it) {
// Wait on the task.
detail::wait_f(*it);
if (it_first_exc == it_f && detail::future_has_exception(*it)) {
// Store an iterator to the throwing future.
it_first_exc = it;
}
}
if (it_first_exc == it_f) {
// No exceptions were raised, just clear everything.
m_ptr->futures.clear();
} else {
// We had a throwing future: preserve it and erase all the other futures.
auto tmp_f(std::move(*it_first_exc));
m_ptr->futures.clear();
m_ptr->futures.emplace_back(std::move(tmp_f));
}
}
/// Status of the island.
/**
* This method will return a pagmo::evolve_status flag indicating the current status of
* asynchronous operations in the island. The flag will be:
*
* * evolve_status::idle if the island is currently not evolving and no exceptions
* were thrown by evolution tasks since the last call to wait_check();
* * evolve_status::busy if the island is evolving and no exceptions
* have (yet) been thrown by evolution tasks since the last call to wait_check();
* * evolve_status::idle_error if the island is currently not evolving and at least one
* evolution task threw an exception since the last call to wait_check();
* * evolve_status::busy_error if the island is currently evolving and at least one
* evolution task has already thrown an exception since the last call to wait_check().
*
* Note that after a call to wait_check(), status() will always return evolve_status::idle,
* and after a call to wait(), status() will always return either evolve_status::idle or
* evolve_status::idle_error.
*
* @return a flag indicating the current status of asynchronous operations in the island.
*/
evolve_status island::status() const
{
// Error flag. It will be set to true if at least one completed task raised an exception.
bool error = false;
// Iterate over all current evolve() tasks.
for (auto &f : m_ptr->futures) {
if (detail::future_running(f)) {
// We have at least one busy task. The return status will be either "busy"
// or "busy_error", depending on whether at least one completed task raised an
// exception.
if (error) {
return evolve_status::busy_error;
}
return evolve_status::busy;
}
// The current task is not running. Check if it generated an error.
// NOTE: the '||' is because this flag, once set to true, needs to stay true.
error = error || detail::future_has_exception(f);
}
if (error) {
// All tasks have finished and at least one generated an error.
return evolve_status::idle_error;
}
// All tasks have finished, no errors generated.
return evolve_status::idle;
}
/// Get the algorithm.
/**
* It is safe to call this method while the island is evolving.
*
* @return a copy of the island's algorithm.
*
* @throws unspecified any exception thrown by threading primitives or by the invoked
* copy constructor.
*/
algorithm island::get_algorithm() const
{
// NOTE: we use this convoluted method involving shared pointers, instead of just
// locking and returning a copy, to accommodate Python. Due to the way the GIL works,
// we need to be very careful about not using the Python interpreter while holding a C++ lock:
// since the interpreter may release the GIL at any time, we can easily run into deadlocks
// due to lock order inversion. So, instead of locking in C++ and then potentially calling into
// Python to perform the copy, we first get a shallow copy of the algo (which involves only C++
// operations), release the C++ lock and then call into Python to perform the copy.
// NOTE: we need to protect with a mutex here because m_ptr->algo might be set concurrently
// by set_algorithm() below, and we guarantee strong thread safety for this method.
// NOTE: it might be possible to replace the locks with atomic operations:
// http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic
// Create a new reference to the internal algo
// (this involves only C++ operations).
std::shared_ptr<algorithm> new_algo_ptr;
{
std::lock_guard<std::mutex> lock(m_ptr->algo_mutex);
new_algo_ptr = m_ptr->algo;
}
// Return a copy.
// NOTE: when exiting the function, the dtor of new_algo_ptr
// will be called. This will result in the refcount
// decreasing, and, if new_algo_ptr is the last existing reference,
// in the call of the dtor of the internal algorithm. This could
// be the case, for instance, if we are using set_algorithm() from
// another thread.
return *new_algo_ptr;
}
/// Set the algorithm.
/**
* It is safe to call this method while the island is evolving.
*
* @param algo the algorithm that will be copied into the island.
*
* @throws unspecified any exception thrown by threading primitives, memory allocation errors
* or the invoked copy constructor.
*/
void island::set_algorithm(const algorithm &algo)
{
// Step 1: create a new shared ptr to a copy of algo.
auto new_algo_ptr = std::make_shared<algorithm>(algo);
// Step 2: init an empty algorithm pointer.
std::shared_ptr<algorithm> old_ptr;
// Step 3: store a reference to the old algo
// in old_ptr, and assign a reference to the
// new algo.
{
std::lock_guard<std::mutex> lock(m_ptr->algo_mutex);
old_ptr = m_ptr->algo;
// NOTE: this assignment will never invoke
// the destructor of the object pointed-to
// by m_ptr->algo, as we made sure
// to create a new reference above.
m_ptr->algo = new_algo_ptr;
}
// NOTE: upon exit, the refcount of old_ptr and
// new_algo_ptr will be decreased, possibly invoking
// the dtor of the contained objects.
}
/// Get the population.
/**
* It is safe to call this method while the island is evolving.
*
* @return a copy of the island's population.
*
* @throws unspecified any exception thrown by threading primitives or by the invoked
* copy constructor.
*/
population island::get_population() const
{
// NOTE: same pattern as in get_algorithm().
std::shared_ptr<population> new_pop_ptr;
{
std::lock_guard<std::mutex> lock(m_ptr->pop_mutex);
new_pop_ptr = m_ptr->pop;
}
return *new_pop_ptr;
}
/// Set the population.
/**
* It is safe to call this method while the island is evolving.
*
* @param pop the population that will be copied into the island.
*
* @throws unspecified any exception thrown by threading primitives, memory allocation errors
* or by the invoked copy constructor.
*/
void island::set_population(const population &pop)
{
// Same pattern as in set_algorithm().
auto new_pop_ptr = std::make_shared<population>(pop);
std::shared_ptr<population> old_ptr;
{
std::lock_guard<std::mutex> lock(m_ptr->pop_mutex);
old_ptr = m_ptr->pop;
m_ptr->pop = new_pop_ptr;
}
}
/// Get the replacement policy.
/**
* @return a copy of the current replacement policy.
*
* @throws unspecified any exception thrown by the copy constructor
* of the replacement policy.
*/
r_policy island::get_r_policy() const
{
// NOTE: replacement/selection policies
// are supposed to provide thread-safe
// copy constructors.
return m_ptr->r_pol;
}
/// Get the selection policy.
/**
* @return a copy of the current selection policy.
*
* @throws unspecified any exception thrown by the copy constructor
* of the selection policy.
*/
s_policy island::get_s_policy() const
{
return m_ptr->s_pol;
}
/// Island's name.
/**
* If the UDI satisfies pagmo::has_name, then this method will return the output of its <tt>%get_name()</tt> method.
* Otherwise, an implementation-defined name based on the type of the UDI will be returned.
*
* It is safe to call this method while the island is evolving.
*
* @return the name of the UDI.
*
* @throws unspecified any exception thrown by the <tt>%get_name()</tt> method of the UDI.
*/
std::string island::get_name() const
{
return m_ptr->isl_ptr->get_name();
}
/// Island's extra info.
/**
* If the UDI satisfies pagmo::has_extra_info, then this method will return the output of its
* <tt>%get_extra_info()</tt> method. Otherwise, an empty string will be returned.
*
* It is safe to call this method while the island is evolving.
*
* @return extra info about the UDI.
*
* @throws unspecified any exception thrown by the <tt>%get_extra_info()</tt> method of the UDI.
*/
std::string island::get_extra_info() const
{
return m_ptr->isl_ptr->get_extra_info();
}
/// Get the type of the UDI.
/**
* \verbatim embed:rst:leading-asterisk
* .. versionadded:: 2.15
*
* This function will return the type
* of the UDI stored within this island
* instance.
* \endverbatim
*
* @return the type of the UDI.
*/
std::type_index island::get_type_index() const
{
return m_ptr->isl_ptr->get_type_index();
}
const void *island::get_ptr() const
{
return m_ptr->isl_ptr->get_ptr();
}
void *island::get_ptr()
{
return m_ptr->isl_ptr->get_ptr();
}
#if !defined(PAGMO_DOXYGEN_INVOKED)
// Stream operator for pagmo::island.
std::ostream &operator<<(std::ostream &os, const island &isl)
{
stream(os, "Island name: ", isl.get_name());
os << "\n\tC++ class name: " << detail::demangle_from_typeid(isl.get_type_index().name()) << '\n';
stream(os, "\n\tStatus: ", isl.status(), "\n\n");
const auto extra_str = isl.get_extra_info();
if (!extra_str.empty()) {
stream(os, "Extra info:\n", extra_str, "\n\n");
}
// Cache out a copy of the population for use below.
const auto pop = isl.get_population();
stream(os, "Algorithm: " + isl.get_algorithm().get_name(), "\n\n");
stream(os, "Problem: " + pop.get_problem().get_name(), "\n\n");
stream(os, "Replacement policy: " + isl.m_ptr->r_pol.get_name(), "\n\n");
stream(os, "Selection policy: " + isl.m_ptr->s_pol.get_name(), "\n\n");
stream(os, "Population size: ", pop.size(), "\n");