Skip to content

Commit

Permalink
Remove manually deleted qubits (by calling qb.__del__() from active_q…
Browse files Browse the repository at this point in the history
…ubits in MainEngine
  • Loading branch information
Damian S. Steiger committed Feb 7, 2018
1 parent bac2277 commit d669ccd
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
3 changes: 2 additions & 1 deletion projectq/cengines/_main.py
Expand Up @@ -236,7 +236,8 @@ def flush(self, deallocate_qubits=False):
id to -1).
"""
if deallocate_qubits:
for qb in self.active_qubits:
while len(self.active_qubits):
qb = self.active_qubits.pop()
qb.__del__()
self.active_qubits = weakref.WeakSet()
self.receive([Command(self, FlushGate(), ([WeakQubitRef(self, -1)],))])
6 changes: 6 additions & 0 deletions projectq/types/_qubit.py
Expand Up @@ -124,6 +124,12 @@ def __del__(self):
"""
if self.id == -1:
return
# If a user directly calls this function, then the qubit gets id == -1
# but stays in active_qubits as it is not yet deleted, hence remove
# it manually (if the garbage collector calls this function, then the
# WeakRef in active qubits is already gone):
if self in self.engine.main_engine.active_qubits:
self.engine.main_engine.active_qubits.remove(self)
weak_copy = WeakQubitRef(self.engine, self.id)
self.id = -1
self.engine.deallocate_qubit(weak_copy)
Expand Down
2 changes: 2 additions & 0 deletions projectq/types/_qubit_test.py
Expand Up @@ -91,6 +91,8 @@ def mock_main_engine():
class MockMainEngine(object):
def __init__(self):
self.num_calls = 0
self.active_qubits = set()
self.main_engine = self

def deallocate_qubit(self, qubit):
self.num_calls += 1
Expand Down

0 comments on commit d669ccd

Please sign in to comment.