Clear all weakrefs and call their callbacks. Called when the owner object is being dropped. PyObject_ClearWeakRefs
(&self, obj: &PyObject)
| 654 | /// Called when the owner object is being dropped. |
| 655 | // PyObject_ClearWeakRefs |
| 656 | fn clear(&self, obj: &PyObject) { |
| 657 | let obj_addr = obj as *const PyObject as usize; |
| 658 | let _lock = weakref_lock::lock(obj_addr); |
| 659 | |
| 660 | // Clear generic cache |
| 661 | self.generic.store(ptr::null_mut(), Ordering::Relaxed); |
| 662 | |
| 663 | // Walk the list, collecting weakrefs with callbacks |
| 664 | let mut callbacks: Vec<(PyRef<PyWeak>, PyObjectRef)> = Vec::new(); |
| 665 | let mut current = NonNull::new(self.head.load(Ordering::Relaxed)); |
| 666 | while let Some(node) = current { |
| 667 | let next = unsafe { WeakLink::pointers(node).as_ref().get_next() }; |
| 668 | |
| 669 | let wr = unsafe { node.as_ref() }; |
| 670 | |
| 671 | // Mark weakref as dead |
| 672 | wr.0.payload |
| 673 | .wr_object |
| 674 | .store(ptr::null_mut(), Ordering::Relaxed); |
| 675 | |
| 676 | // Unlink from list |
| 677 | unsafe { |
| 678 | let mut ptrs = WeakLink::pointers(node); |
| 679 | ptrs.as_mut().set_prev(None); |
| 680 | ptrs.as_mut().set_next(None); |
| 681 | } |
| 682 | |
| 683 | // Collect callback only if we can still acquire a strong ref. |
| 684 | if wr.0.ref_count.safe_inc() { |
| 685 | let wr_ref = unsafe { PyRef::from_raw(wr as *const Py<PyWeak>) }; |
| 686 | let cb = unsafe { wr.0.payload.callback.get().replace(None) }; |
| 687 | if let Some(cb) = cb { |
| 688 | callbacks.push((wr_ref, cb)); |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | current = next; |
| 693 | } |
| 694 | self.head.store(ptr::null_mut(), Ordering::Relaxed); |
| 695 | |
| 696 | // Invoke callbacks outside the lock |
| 697 | drop(_lock); |
| 698 | for (wr, cb) in callbacks { |
| 699 | crate::vm::thread::with_vm(&cb, |vm| { |
| 700 | let _ = cb.call((wr.clone(),), vm); |
| 701 | }); |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | /// Clear all weakrefs but DON'T call callbacks. Instead, return them for later invocation. |
| 706 | /// Used by GC to ensure ALL weakrefs are cleared BEFORE any callbacks are invoked. |
no test coverage detected