How to regularly clean up memory in Python when creating threads?
In Python, you can create threads using the threading module and periodically clean up memory using the gc module.
Below is a sample code demonstrating how to use threads to periodically clean up memory.
import threading
import gc
def memory_cleanup():
while True:
# 执行垃圾回收
gc.collect()
# 在这里可以添加其他的内存清理操作
# 休眠一段时间,例如每10秒清理一次内存
time.sleep(10)
# 创建一个线程来执行内存清理任务
cleanup_thread = threading.Thread(target=memory_cleanup)
cleanup_thread.daemon = True # 设置为守护线程,随主线程退出而退出
cleanup_thread.start()
# 主线程的任务
# ...
# 等待所有线程运行完毕
cleanup_thread.join()
In the code above, we have created a memory_cleanup function as a thread task, which regularly performs garbage collection operations in an infinite loop and can include other memory cleaning operations. By creating and starting this thread in the main thread, we can achieve the functionality of periodic memory cleanup.