由於Python的datetime和time中的_strptime方法不支持多線程,運行時會報錯:AttributeError: _strptime
code:
# -*- coding:utf-8 -*- import threading import time import datetime ISO8601_INT_SECONDS = '%Y-%m-%dT%H:%M:%SZ' expiry_string = "2018-01-04T04:23:02Z" def test_thread(expiry_string): expiry = datetime.datetime.strptime( expiry_string, ISO8601_INT_SECONDS) print expiry threads = [] for i in xrange(5): t = threading.Thread(target=test_thread, args=(expiry_string,)) threads.append(t) for t in threads: t.start() for t in threads: t.join() print "every thing is ok!!!"
會報錯誤:AttributeError: 'module' object has no attribute '_strptime'
解決方案:
1.在調用_strptime的地方加鎖(推薦)
方式1.
c = threading.RLock()
def f():
with c:
datetime.datetime.strptime("20100101","%Y%m%d")
def f():
with c:
datetime.datetime.strptime("20100101","%Y%m%d")
方式2:
LOCK = thread.allocate_lock()
LOCK.acquire()
datetime.datetime.strptime("20100101","%Y%m%d")
LOCK.release()
2、在線程啟動前調用一次_strptime(原因是報了這個錯),不是很推薦
方式1、import _strptime
方式2、在調用線程前執行一次: datetime.datetime.strptime("20100101","%Y%m%d")。(似乎對我們不合適)
參考資料:
