gc.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #pragma once
  2. #include "common.h"
  3. #include "memory.h"
  4. #include "obj.h"
  5. #include "codeobject.h"
  6. #include "namedict.h"
  7. namespace pkpy {
  8. struct ManagedHeap{
  9. std::vector<PyObject*> _no_gc;
  10. std::vector<PyObject*> gen;
  11. VM* vm;
  12. void (*_gc_on_delete)(VM*, PyObject*) = nullptr;
  13. void (*_gc_marker_ex)(VM*) = nullptr;
  14. ManagedHeap(VM* vm): vm(vm) {}
  15. int gc_threshold = PK_GC_MIN_THRESHOLD;
  16. int gc_counter = 0;
  17. /********************/
  18. int _gc_lock_counter = 0;
  19. struct ScopeLock{
  20. ManagedHeap* heap;
  21. ScopeLock(ManagedHeap* heap): heap(heap){
  22. heap->_gc_lock_counter++;
  23. }
  24. ~ScopeLock(){
  25. heap->_gc_lock_counter--;
  26. }
  27. };
  28. ScopeLock gc_scope_lock(){
  29. return ScopeLock(this);
  30. }
  31. /********************/
  32. template<typename T, typename... Args>
  33. PyObject* gcnew(Type type, Args&&... args){
  34. using __T = Py_<std::decay_t<T>>;
  35. // https://github.com/pocketpy/pocketpy/issues/94#issuecomment-1594784476
  36. PyObject* obj = new(pool64_alloc<__T>()) Py_<std::decay_t<T>>(type, std::forward<Args>(args)...);
  37. gen.push_back(obj);
  38. gc_counter++;
  39. return obj;
  40. }
  41. template<typename T, typename... Args>
  42. PyObject* _new(Type type, Args&&... args){
  43. using __T = Py_<std::decay_t<T>>;
  44. // https://github.com/pocketpy/pocketpy/issues/94#issuecomment-1594784476
  45. PyObject* obj = new(pool64_alloc<__T>()) Py_<std::decay_t<T>>(type, std::forward<Args>(args)...);
  46. obj->gc.enabled = false;
  47. _no_gc.push_back(obj);
  48. return obj;
  49. }
  50. #if PK_DEBUG_GC_STATS
  51. inline static std::map<Type, int> deleted;
  52. #endif
  53. int sweep();
  54. void _auto_collect();
  55. bool _should_auto_collect() const { return gc_counter >= gc_threshold; }
  56. int collect();
  57. void mark();
  58. ~ManagedHeap();
  59. };
  60. } // namespace pkpy