Python多线程下存在_strptime的问题


由于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")
方式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")。(似乎对我们不合适)
 
参考资料:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM