Cleanup threading module state that should not exist after a fork.
()
| 1612 | |
| 1613 | |
| 1614 | def _after_fork(): |
| 1615 | """ |
| 1616 | Cleanup threading module state that should not exist after a fork. |
| 1617 | """ |
| 1618 | # Reset _active_limbo_lock, in case we forked while the lock was held |
| 1619 | # by another (non-forked) thread. http://bugs.python.org/issue874900 |
| 1620 | global _active_limbo_lock, _main_thread |
| 1621 | global _shutdown_locks_lock, _shutdown_locks |
| 1622 | _active_limbo_lock = RLock() |
| 1623 | |
| 1624 | # fork() only copied the current thread; clear references to others. |
| 1625 | new_active = {} |
| 1626 | |
| 1627 | try: |
| 1628 | current = _active[get_ident()] |
| 1629 | except KeyError: |
| 1630 | # fork() was called in a thread which was not spawned |
| 1631 | # by threading.Thread. For example, a thread spawned |
| 1632 | # by thread.start_new_thread(). |
| 1633 | current = _MainThread() |
| 1634 | |
| 1635 | _main_thread = current |
| 1636 | |
| 1637 | # reset _shutdown() locks: threads re-register their _tstate_lock below |
| 1638 | _shutdown_locks_lock = _allocate_lock() |
| 1639 | _shutdown_locks = set() |
| 1640 | |
| 1641 | with _active_limbo_lock: |
| 1642 | # Dangling thread instances must still have their locks reset, |
| 1643 | # because someone may join() them. |
| 1644 | threads = set(_enumerate()) |
| 1645 | threads.update(_dangling) |
| 1646 | for thread in threads: |
| 1647 | # Any lock/condition variable may be currently locked or in an |
| 1648 | # invalid state, so we reinitialize them. |
| 1649 | if thread is current: |
| 1650 | # There is only one active thread. We reset the ident to |
| 1651 | # its new value since it can have changed. |
| 1652 | thread._reset_internal_locks(True) |
| 1653 | ident = get_ident() |
| 1654 | if isinstance(thread, _DummyThread): |
| 1655 | thread.__class__ = _MainThread |
| 1656 | thread._name = 'MainThread' |
| 1657 | thread._daemonic = False |
| 1658 | thread._set_tstate_lock() |
| 1659 | thread._ident = ident |
| 1660 | new_active[ident] = thread |
| 1661 | else: |
| 1662 | # All the others are already stopped. |
| 1663 | thread._reset_internal_locks(False) |
| 1664 | thread._stop() |
| 1665 | |
| 1666 | _limbo.clear() |
| 1667 | _active.clear() |
| 1668 | _active.update(new_active) |
| 1669 | assert len(_active) == 1 |
| 1670 | |
| 1671 |
nothing calls this directly
no test coverage detected