sigslot.h (21236B)
1 // sigslot.h: Signal/Slot classes 2 // 3 // Written by Sarah Thompson (sarah@telergy.com) 2002. 4 // 5 // License: Public domain. You are free to use this code however you like, with 6 // the proviso that the author takes on no responsibility or liability for any 7 // use. 8 // 9 // QUICK DOCUMENTATION 10 // 11 // (see also the full documentation at http://sigslot.sourceforge.net/) 12 // 13 // #define switches 14 // SIGSLOT_PURE_ISO: 15 // Define this to force ISO C++ compliance. This also disables all of 16 // the thread safety support on platforms where it is available. 17 // 18 // SIGSLOT_USE_POSIX_THREADS: 19 // Force use of Posix threads when using a C++ compiler other than gcc 20 // on a platform that supports Posix threads. (When using gcc, this is 21 // the default - use SIGSLOT_PURE_ISO to disable this if necessary) 22 // 23 // SIGSLOT_DEFAULT_MT_POLICY: 24 // Where thread support is enabled, this defaults to 25 // multi_threaded_global. Otherwise, the default is single_threaded. 26 // #define this yourself to override the default. In pure ISO mode, 27 // anything other than single_threaded will cause a compiler error. 28 // 29 // PLATFORM NOTES 30 // 31 // Win32: 32 // On Win32, the WEBRTC_WIN symbol must be #defined. Most mainstream 33 // compilers do this by default, but you may need to define it yourself 34 // if your build environment is less standard. This causes the Win32 35 // thread support to be compiled in and used automatically. 36 // 37 // Unix/Linux/BSD, etc.: 38 // If you're using gcc, it is assumed that you have Posix threads 39 // available, so they are used automatically. You can override this (as 40 // under Windows) with the SIGSLOT_PURE_ISO switch. If you're using 41 // something other than gcc but still want to use Posix threads, you 42 // need to #define SIGSLOT_USE_POSIX_THREADS. 43 // 44 // ISO C++: 45 // If none of the supported platforms are detected, or if 46 // SIGSLOT_PURE_ISO is defined, all multithreading support is turned 47 // off, along with any code that might cause a pure ISO C++ environment 48 // to complain. Before you ask, gcc -ansi -pedantic won't compile this 49 // library, but gcc -ansi is fine. Pedantic mode seems to throw a lot of 50 // errors that aren't really there. If you feel like investigating this, 51 // please contact the author. 52 // 53 // 54 // THREADING MODES 55 // 56 // single_threaded: 57 // Your program is assumed to be single threaded from the point of view 58 // of signal/slot usage (i.e. all objects using signals and slots are 59 // created and destroyed from a single thread). Behaviour if objects are 60 // destroyed concurrently is undefined (i.e. you'll get the occasional 61 // segmentation fault/memory exception). 62 // 63 // multi_threaded_global: 64 // Your program is assumed to be multi threaded. Objects using signals 65 // and slots can be safely created and destroyed from any thread, even 66 // when connections exist. In multi_threaded_global mode, this is 67 // achieved by a single global mutex (actually a critical section on 68 // Windows because they are faster). This option uses less OS resources, 69 // but results in more opportunities for contention, possibly resulting 70 // in more context switches than are strictly necessary. 71 // 72 // multi_threaded_local: 73 // Behaviour in this mode is essentially the same as 74 // multi_threaded_global, except that each signal, and each object that 75 // inherits has_slots, all have their own mutex/critical section. In 76 // practice, this means that mutex collisions (and hence context 77 // switches) only happen if they are absolutely essential. However, on 78 // some platforms, creating a lot of mutexes can slow down the whole OS, 79 // so use this option with care. 80 // 81 // USING THE LIBRARY 82 // 83 // See the full documentation at http://sigslot.sourceforge.net/ 84 // 85 // Libjingle specific: 86 // 87 // This file has been modified such that has_slots and signalx do not have to be 88 // using the same threading requirements. E.g. it is possible to connect a 89 // has_slots<single_threaded> and signal0<multi_threaded_local> or 90 // has_slots<multi_threaded_local> and signal0<single_threaded>. 91 // If has_slots is single threaded the user must ensure that it is not trying 92 // to connect or disconnect to signalx concurrently or data race may occur. 93 // If signalx is single threaded the user must ensure that disconnect, connect 94 // or signal is not happening concurrently or data race may occur. 95 96 #ifndef RTC_BASE_SIGSLOT_H_ 97 #define RTC_BASE_SIGSLOT_H_ 98 99 #include <stdlib.h> 100 101 #include <cstring> 102 #include <list> 103 #include <set> 104 105 // On our copy of sigslot.h, we set single threading as default. 106 #define SIGSLOT_DEFAULT_MT_POLICY single_threaded 107 108 #if defined(SIGSLOT_PURE_ISO) || \ 109 (!defined(WEBRTC_WIN) && !defined(__GNUG__) && \ 110 !defined(SIGSLOT_USE_POSIX_THREADS)) 111 # define _SIGSLOT_SINGLE_THREADED 112 #elif defined(WEBRTC_WIN) 113 # define _SIGSLOT_HAS_WIN32_THREADS 114 # if !defined(WIN32_LEAN_AND_MEAN) 115 # define WIN32_LEAN_AND_MEAN 116 # endif 117 # include "rtc_base/win32.h" 118 #elif (defined(__GNUG__) || defined(SIGSLOT_USE_POSIX_THREADS)) && \ 119 !defined(__MINGW32__) 120 # define _SIGSLOT_HAS_POSIX_THREADS 121 # include <pthread.h> 122 #else 123 # define _SIGSLOT_SINGLE_THREADED 124 #endif 125 126 #ifndef SIGSLOT_DEFAULT_MT_POLICY 127 # ifdef _SIGSLOT_SINGLE_THREADED 128 # define SIGSLOT_DEFAULT_MT_POLICY single_threaded 129 # else 130 # define SIGSLOT_DEFAULT_MT_POLICY multi_threaded_local 131 # endif 132 #endif 133 134 // TODO: change this namespace to rtc? 135 namespace sigslot { 136 137 class single_threaded { 138 public: 139 void lock() {} 140 void unlock() {} 141 }; 142 143 #ifdef _SIGSLOT_HAS_WIN32_THREADS 144 // The multi threading policies only get compiled in if they are enabled. 145 class multi_threaded_global { 146 public: 147 multi_threaded_global() { 148 static bool isinitialised = false; 149 150 if (!isinitialised) { 151 InitializeCriticalSection(get_critsec()); 152 isinitialised = true; 153 } 154 } 155 156 void lock() { EnterCriticalSection(get_critsec()); } 157 158 void unlock() { LeaveCriticalSection(get_critsec()); } 159 160 private: 161 CRITICAL_SECTION* get_critsec() { 162 static CRITICAL_SECTION g_critsec; 163 return &g_critsec; 164 } 165 }; 166 167 class multi_threaded_local { 168 public: 169 multi_threaded_local() { InitializeCriticalSection(&m_critsec); } 170 171 multi_threaded_local(const multi_threaded_local&) { 172 InitializeCriticalSection(&m_critsec); 173 } 174 175 ~multi_threaded_local() { DeleteCriticalSection(&m_critsec); } 176 177 void lock() { EnterCriticalSection(&m_critsec); } 178 179 void unlock() { LeaveCriticalSection(&m_critsec); } 180 181 private: 182 CRITICAL_SECTION m_critsec; 183 }; 184 #endif // _SIGSLOT_HAS_WIN32_THREADS 185 186 #ifdef _SIGSLOT_HAS_POSIX_THREADS 187 // The multi threading policies only get compiled in if they are enabled. 188 class multi_threaded_global { 189 public: 190 void lock() { pthread_mutex_lock(get_mutex()); } 191 void unlock() { pthread_mutex_unlock(get_mutex()); } 192 193 private: 194 static pthread_mutex_t* get_mutex(); 195 }; 196 197 class multi_threaded_local { 198 public: 199 multi_threaded_local() { pthread_mutex_init(&m_mutex, nullptr); } 200 multi_threaded_local(const multi_threaded_local&) { 201 pthread_mutex_init(&m_mutex, nullptr); 202 } 203 ~multi_threaded_local() { pthread_mutex_destroy(&m_mutex); } 204 void lock() { pthread_mutex_lock(&m_mutex); } 205 void unlock() { pthread_mutex_unlock(&m_mutex); } 206 207 private: 208 pthread_mutex_t m_mutex; 209 }; 210 #endif // _SIGSLOT_HAS_POSIX_THREADS 211 212 template <class mt_policy> 213 class lock_block { 214 public: 215 mt_policy* m_mutex; 216 217 explicit lock_block(mt_policy* mtx) : m_mutex(mtx) { m_mutex->lock(); } 218 219 ~lock_block() { m_mutex->unlock(); } 220 }; 221 222 class _signal_base_interface; 223 224 class has_slots_interface { 225 private: 226 typedef void (*signal_connect_t)(has_slots_interface* self, 227 _signal_base_interface* sender); 228 typedef void (*signal_disconnect_t)(has_slots_interface* self, 229 _signal_base_interface* sender); 230 typedef void (*disconnect_all_t)(has_slots_interface* self); 231 232 const signal_connect_t m_signal_connect; 233 const signal_disconnect_t m_signal_disconnect; 234 const disconnect_all_t m_disconnect_all; 235 236 protected: 237 has_slots_interface(signal_connect_t conn, signal_disconnect_t disc, 238 disconnect_all_t disc_all) 239 : m_signal_connect(conn), 240 m_signal_disconnect(disc), 241 m_disconnect_all(disc_all) {} 242 243 // Doesn't really need to be virtual, but is for backwards compatibility 244 // (it was virtual in a previous version of sigslot). 245 virtual ~has_slots_interface() = default; 246 247 public: 248 void signal_connect(_signal_base_interface* sender) { 249 m_signal_connect(this, sender); 250 } 251 252 void signal_disconnect(_signal_base_interface* sender) { 253 m_signal_disconnect(this, sender); 254 } 255 256 void disconnect_all() { m_disconnect_all(this); } 257 }; 258 259 class _signal_base_interface { 260 private: 261 typedef void (*slot_disconnect_t)(_signal_base_interface* self, 262 has_slots_interface* pslot); 263 typedef void (*slot_duplicate_t)(_signal_base_interface* self, 264 const has_slots_interface* poldslot, 265 has_slots_interface* pnewslot); 266 267 const slot_disconnect_t m_slot_disconnect; 268 const slot_duplicate_t m_slot_duplicate; 269 270 protected: 271 _signal_base_interface(slot_disconnect_t disc, slot_duplicate_t dupl) 272 : m_slot_disconnect(disc), m_slot_duplicate(dupl) {} 273 274 ~_signal_base_interface() = default; 275 276 public: 277 void slot_disconnect(has_slots_interface* pslot) { 278 m_slot_disconnect(this, pslot); 279 } 280 281 void slot_duplicate(const has_slots_interface* poldslot, 282 has_slots_interface* pnewslot) { 283 m_slot_duplicate(this, poldslot, pnewslot); 284 } 285 }; 286 287 class _opaque_connection { 288 private: 289 typedef void (*emit_t)(const _opaque_connection*); 290 template <typename FromT, typename ToT> 291 union union_caster { 292 FromT from; 293 ToT to; 294 }; 295 296 emit_t pemit; 297 has_slots_interface* pdest; 298 // Pointers to member functions may be up to 16 bytes for virtual classes, 299 // so make sure we have enough space to store it. 300 unsigned char pmethod[16]; 301 302 public: 303 template <typename DestT, typename... Args> 304 _opaque_connection(DestT* pd, void (DestT::*pm)(Args...)) : pdest(pd) { 305 typedef void (DestT::*pm_t)(Args...); 306 static_assert(sizeof(pm_t) <= sizeof(pmethod), 307 "Size of slot function pointer too large."); 308 309 std::memcpy(pmethod, &pm, sizeof(pm_t)); 310 311 typedef void (*em_t)(const _opaque_connection* self, Args...); 312 union_caster<em_t, emit_t> caster2; 313 caster2.from = &_opaque_connection::emitter<DestT, Args...>; 314 pemit = caster2.to; 315 } 316 317 has_slots_interface* getdest() const { return pdest; } 318 319 _opaque_connection duplicate(has_slots_interface* newtarget) const { 320 _opaque_connection res = *this; 321 res.pdest = newtarget; 322 return res; 323 } 324 325 // Just calls the stored "emitter" function pointer stored at construction 326 // time. 327 template <typename... Args> 328 void emit(Args... args) const { 329 typedef void (*em_t)(const _opaque_connection*, Args...); 330 union_caster<emit_t, em_t> caster; 331 caster.from = pemit; 332 (caster.to)(this, args...); 333 } 334 335 private: 336 template <typename DestT, typename... Args> 337 static void emitter(const _opaque_connection* self, Args... args) { 338 typedef void (DestT::*pm_t)(Args...); 339 pm_t pm; 340 std::memcpy(&pm, self->pmethod, sizeof(pm_t)); 341 (static_cast<DestT*>(self->pdest)->*(pm))(args...); 342 } 343 }; 344 345 template <class mt_policy> 346 class _signal_base : public _signal_base_interface, public mt_policy { 347 protected: 348 typedef std::list<_opaque_connection> connections_list; 349 350 _signal_base() 351 : _signal_base_interface(&_signal_base::do_slot_disconnect, 352 &_signal_base::do_slot_duplicate), 353 m_current_iterator(m_connected_slots.end()) {} 354 355 ~_signal_base() { disconnect_all(); } 356 357 private: 358 _signal_base& operator=(_signal_base const& that); 359 360 public: 361 _signal_base(const _signal_base& o) 362 : _signal_base_interface(&_signal_base::do_slot_disconnect, 363 &_signal_base::do_slot_duplicate), 364 m_current_iterator(m_connected_slots.end()) { 365 lock_block<mt_policy> lock(this); 366 for (const auto& connection : o.m_connected_slots) { 367 connection.getdest()->signal_connect(this); 368 m_connected_slots.push_back(connection); 369 } 370 } 371 372 bool is_empty() { 373 lock_block<mt_policy> lock(this); 374 return m_connected_slots.empty(); 375 } 376 377 void disconnect_all() { 378 lock_block<mt_policy> lock(this); 379 380 while (!m_connected_slots.empty()) { 381 has_slots_interface* pdest = m_connected_slots.front().getdest(); 382 m_connected_slots.pop_front(); 383 pdest->signal_disconnect(static_cast<_signal_base_interface*>(this)); 384 } 385 // If disconnect_all is called while the signal is firing, advance the 386 // current slot iterator to the end to avoid an invalidated iterator from 387 // being dereferenced. 388 m_current_iterator = m_connected_slots.end(); 389 } 390 391 #if !defined(NDEBUG) 392 bool connected(has_slots_interface* pclass) { 393 lock_block<mt_policy> lock(this); 394 connections_list::const_iterator it = m_connected_slots.begin(); 395 connections_list::const_iterator itEnd = m_connected_slots.end(); 396 while (it != itEnd) { 397 if (it->getdest() == pclass) return true; 398 ++it; 399 } 400 return false; 401 } 402 #endif 403 404 void disconnect(has_slots_interface* pclass) { 405 lock_block<mt_policy> lock(this); 406 connections_list::iterator it = m_connected_slots.begin(); 407 connections_list::iterator itEnd = m_connected_slots.end(); 408 409 while (it != itEnd) { 410 if (it->getdest() == pclass) { 411 // If we're currently using this iterator because the signal is firing, 412 // advance it to avoid it being invalidated. 413 if (m_current_iterator == it) { 414 m_current_iterator = m_connected_slots.erase(it); 415 } else { 416 m_connected_slots.erase(it); 417 } 418 pclass->signal_disconnect(static_cast<_signal_base_interface*>(this)); 419 return; 420 } 421 ++it; 422 } 423 } 424 425 private: 426 static void do_slot_disconnect(_signal_base_interface* p, 427 has_slots_interface* pslot) { 428 _signal_base* const self = static_cast<_signal_base*>(p); 429 lock_block<mt_policy> lock(self); 430 connections_list::iterator it = self->m_connected_slots.begin(); 431 connections_list::iterator itEnd = self->m_connected_slots.end(); 432 433 while (it != itEnd) { 434 connections_list::iterator itNext = it; 435 ++itNext; 436 437 if (it->getdest() == pslot) { 438 // If we're currently using this iterator because the signal is firing, 439 // advance it to avoid it being invalidated. 440 if (self->m_current_iterator == it) { 441 self->m_current_iterator = self->m_connected_slots.erase(it); 442 } else { 443 self->m_connected_slots.erase(it); 444 } 445 } 446 447 it = itNext; 448 } 449 } 450 451 static void do_slot_duplicate(_signal_base_interface* p, 452 const has_slots_interface* oldtarget, 453 has_slots_interface* newtarget) { 454 _signal_base* const self = static_cast<_signal_base*>(p); 455 lock_block<mt_policy> lock(self); 456 connections_list::iterator it = self->m_connected_slots.begin(); 457 connections_list::iterator itEnd = self->m_connected_slots.end(); 458 459 while (it != itEnd) { 460 if (it->getdest() == oldtarget) { 461 self->m_connected_slots.push_back(it->duplicate(newtarget)); 462 } 463 464 ++it; 465 } 466 } 467 468 protected: 469 connections_list m_connected_slots; 470 471 // Used to handle a slot being disconnected while a signal is 472 // firing (iterating m_connected_slots). 473 connections_list::iterator m_current_iterator; 474 bool m_erase_current_iterator = false; 475 }; 476 477 template <class mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 478 class has_slots : public has_slots_interface, public mt_policy { 479 private: 480 typedef std::set<_signal_base_interface*> sender_set; 481 typedef sender_set::const_iterator const_iterator; 482 483 public: 484 has_slots() 485 : has_slots_interface(&has_slots::do_signal_connect, 486 &has_slots::do_signal_disconnect, 487 &has_slots::do_disconnect_all) {} 488 489 has_slots(has_slots const& o) 490 : has_slots_interface(&has_slots::do_signal_connect, 491 &has_slots::do_signal_disconnect, 492 &has_slots::do_disconnect_all) { 493 lock_block<mt_policy> lock(this); 494 for (auto* sender : o.m_senders) { 495 sender->slot_duplicate(&o, this); 496 m_senders.insert(sender); 497 } 498 } 499 500 ~has_slots() { this->disconnect_all(); } 501 502 private: 503 has_slots& operator=(has_slots const&); 504 505 static void do_signal_connect(has_slots_interface* p, 506 _signal_base_interface* sender) { 507 has_slots* const self = static_cast<has_slots*>(p); 508 lock_block<mt_policy> lock(self); 509 self->m_senders.insert(sender); 510 } 511 512 static void do_signal_disconnect(has_slots_interface* p, 513 _signal_base_interface* sender) { 514 has_slots* const self = static_cast<has_slots*>(p); 515 lock_block<mt_policy> lock(self); 516 self->m_senders.erase(sender); 517 } 518 519 static void do_disconnect_all(has_slots_interface* p) { 520 has_slots* const self = static_cast<has_slots*>(p); 521 lock_block<mt_policy> lock(self); 522 while (!self->m_senders.empty()) { 523 std::set<_signal_base_interface*> senders; 524 senders.swap(self->m_senders); 525 const_iterator it = senders.begin(); 526 const_iterator itEnd = senders.end(); 527 528 while (it != itEnd) { 529 _signal_base_interface* s = *it; 530 ++it; 531 s->slot_disconnect(p); 532 } 533 } 534 } 535 536 private: 537 sender_set m_senders; 538 }; 539 540 template <class mt_policy, typename... Args> 541 class signal_with_thread_policy : public _signal_base<mt_policy> { 542 private: 543 typedef _signal_base<mt_policy> base; 544 545 protected: 546 typedef typename base::connections_list connections_list; 547 548 public: 549 signal_with_thread_policy() = default; 550 551 template <class desttype> 552 void connect(desttype* pclass, void (desttype::*pmemfun)(Args...)) { 553 lock_block<mt_policy> lock(this); 554 this->m_connected_slots.push_back(_opaque_connection(pclass, pmemfun)); 555 pclass->signal_connect(static_cast<_signal_base_interface*>(this)); 556 } 557 558 void emit(Args... args) { 559 lock_block<mt_policy> lock(this); 560 this->m_current_iterator = this->m_connected_slots.begin(); 561 while (this->m_current_iterator != this->m_connected_slots.end()) { 562 _opaque_connection const& conn = *this->m_current_iterator; 563 ++(this->m_current_iterator); 564 conn.emit<Args...>(args...); 565 } 566 } 567 568 void operator()(Args... args) { emit(args...); } 569 }; 570 571 // Alias with default thread policy. Needed because both default arguments 572 // and variadic template arguments must go at the end of the list, so we 573 // can't have both at once. 574 template <typename... Args> 575 using signal = signal_with_thread_policy<SIGSLOT_DEFAULT_MT_POLICY, Args...>; 576 577 // The previous verion of sigslot didn't use variadic templates, so you would 578 // need to write "sigslot::signal2<Arg1, Arg2>", for example. 579 // Now you can just write "sigslot::signal<Arg1, Arg2>", but these aliases 580 // exist for backwards compatibility. 581 template <typename mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 582 using signal0 = signal_with_thread_policy<mt_policy>; 583 584 template <typename A1, typename mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 585 using signal1 = signal_with_thread_policy<mt_policy, A1>; 586 587 template <typename A1, typename A2, 588 typename mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 589 using signal2 = signal_with_thread_policy<mt_policy, A1, A2>; 590 591 template <typename A1, typename A2, typename A3, 592 typename mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 593 using signal3 = signal_with_thread_policy<mt_policy, A1, A2, A3>; 594 595 template <typename A1, typename A2, typename A3, typename A4, 596 typename mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 597 using signal4 = signal_with_thread_policy<mt_policy, A1, A2, A3, A4>; 598 599 template <typename A1, typename A2, typename A3, typename A4, typename A5, 600 typename mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 601 using signal5 = signal_with_thread_policy<mt_policy, A1, A2, A3, A4, A5>; 602 603 template <typename A1, typename A2, typename A3, typename A4, typename A5, 604 typename A6, typename mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 605 using signal6 = signal_with_thread_policy<mt_policy, A1, A2, A3, A4, A5, A6>; 606 607 template <typename A1, typename A2, typename A3, typename A4, typename A5, 608 typename A6, typename A7, 609 typename mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 610 using signal7 = 611 signal_with_thread_policy<mt_policy, A1, A2, A3, A4, A5, A6, A7>; 612 613 template <typename A1, typename A2, typename A3, typename A4, typename A5, 614 typename A6, typename A7, typename A8, 615 typename mt_policy = SIGSLOT_DEFAULT_MT_POLICY> 616 using signal8 = 617 signal_with_thread_policy<mt_policy, A1, A2, A3, A4, A5, A6, A7, A8>; 618 619 } // namespace sigslot 620 621 #endif // RTC_BASE_SIGSLOT_H_