I have a program in which I need to store a global variable into a file. I am doing this using the pickle
module.
I have another thread
(Daemon=False
, from threading
module) which sometimes changes the value of the global variable. The value is also modified in global scope(the main program).
I am dumping the value of the variable into a .pkl
file every 5 seconds (using another thread
from threading
module).
But I found the following error when dump
method was executed:
TypeError: can't pickle _thread.lock objects
Why is this happening? And what can I do to fix it?
Note: I have found some similar answers with multiprocessing
module. But I need an answer for threading
module.
Code:
def save_state():
while True:
global variable
lastSession = open('lastSession.pkl', 'wb')
# error occurs on this line
pickle.dump(variable, lastSession)
lastSession.close()
time.sleep(5)
state_thread = threading.Thread(target = save_state)
state_thread.setDaemon(False)
state_thread.start()
# variable is changed outside this function and also in another thread(not state_thread).