2016-09-30 52 views
0

我有一些代碼很好地工作。這是一個通過日期列表的while循環,在我的硬盤上找到與這些日期相對應的文件,對這些文件進行一些計算,然後使用以下命令輸出到「results.csv」文件:蟒蛇,多線程,安全地使用普通文件上的熊貓「to_csv」?

my_df.to_csv("results.csv",mode = 'a') 

我想知道是否可以安全地爲每個日期創建一個新的線程,並在幾個日期一次調用while循環中的東西?

我的代碼:

import datetime, time, os 
import sys 
import threading 
import helperPY #a python file containing the logic I need 

class myThread (threading.Thread): 
    def __init__(self, threadID, name, counter,sn, m_date): 
     threading.Thread.__init__(self) 
     self.threadID = threadID 
     self.name = name 
     self.counter = counter 
     self.sn = sn 
     self.m_date = m_date 
    def run(self): 
     print "Starting " + self.name 
     m_runThis(sn, m_date) 
     print "Exiting " + self.name 

def m_runThis(sn, m_date): 
    helperPY.helpFn(sn,m_date) #this is where the "my_df.to_csv()" is called 

sn = 'XXXXXX' 
today=datetime.datetime(2016,9,22) # 
yesterday=datetime.datetime(2016,6,13) 

threadList = [] 
i_threadlist=0 
while(today>yesterday): 
    threadList.append(myThread(i_threadlist, str(today), i_threadlist,sn,today)) 
    threadList[i_threadlist].start() 
    i_threadlist = i_threadlist +1 
    today = today-datetime.timedelta(1) 

回答

1

寫在多線程的文件是不是安全。但是您可以創建lock來保護這一個操作,同時讓其他操作平行運行。您to_csv沒有顯示,但你可以創建鎖

csv_output_lock = threading.Lock() 

,並把它傳遞給helperPY.helpFn。當你的操作,做

with csv_output_lock: 
    my_df.to_csv("results.csv",mode = 'a') 

你得到並行進行其他操作 - 服從當然GIL - 但該文件的訪問是受保護的。

+0

我必須在調用helperFn()之前/之後獲取/釋放鎖嗎? –

+1

如果你使用'with'子句進行操作,則鎖定在進入該模塊時獲取,並在退出時自動釋放。但是,只有當它只包裝了一些代碼時,鎖纔有用。如果你所有的工作都是在'helperFn'內完成的,並且你鎖定了'helperFn'的全部內容,那麼你已經擊敗了該池的任何優勢。 – tdelaney

+0

理論上這是不安全的,但實際上Python的線程受到全局解釋器鎖定的限制。除非代碼偏離到釋放這個鎖的C擴展,否則即使線程模塊也在排隊,我相信這應該使IO安全。意見? – Mai