发上等愿,结中等缘,享下等福;择高处立,寻平处住,向宽处行

Brick walls are there for a reason :they let us prove how badly we want things

代码改变世界

Python多线程下存在_strptime的问题

  kowme  阅读(3269)  评论(0编辑  收藏  举报

由于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")。(似乎对我们不合适)
 
参考资料:
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架

It's not who you are underneath, it's what you do that defines you

Brick walls are there for a reason :they let us prove how badly we want things

点击右上角即可分享
微信分享提示