Python 多線程,文件io

import os  #目錄操做

def writeFile():
    fo = open("foo.txt", "a+") #打開一個文件,第二個參數爲打開的模式:r 只讀,r+讀寫 w只寫 w+讀寫 wb二進制方式只寫 a 追加
    print ("文件名: ", fo.name)
    print("是否已關閉 : ", fo.closed)
    print("訪問模式 : ", fo.mode)
    fo.write("www.runoob.com!\nVery good site!")
    fo.close() #刷新緩衝區裏任何還沒寫入的信息,並關閉該文件,這以後便不能再進行寫入
    print("是否已關閉 : ", fo.closed)
def readFile():
    fo = open("foo.txt", "r+")  # 打開一個文件,第二個參數爲打開的模式:r 只讀,r+讀寫 w只寫 w+讀寫 wb二進制方式只寫 a 追加
    print("文件名: ", fo.name)
    print("是否已關閉 : ", fo.closed)
    print("訪問模式 : ", fo.mode)
    str = fo.read(10);
    print("讀取的字符串是 : ", str)
    position = fo.tell();
    print("指針當前文件位置 : ", position)
    # 把指針再次從新定位到文件開頭
    position = fo.seek(0,0);
    str = fo.read(10);
    print("從新讀取字符串 : ", str)
    fo.close()  # 刷新緩衝區裏任何還沒寫入的信息,並關閉該文件,這以後便不能再進行寫入
    print("是否已關閉 : ", fo.closed)
#重命名
def dirFile():
    fo = open("foo.txt", "w+")#
    fo.close()  # 刷新緩衝區裏任何還沒寫入的信息,並關閉該文件,這以後便不能再進行寫入
    print("建立文件名: ", fo.name)
    os.rename("foo.txt","oof.txt")
    print("修改文件名: ", fo.name)
    os.remove("oof.txt")
    # 建立目錄test
    #os.mkdir("test")
    # 刪除」/tmp/test」目錄
    #os.rmdir("/tmp/test")
    # 給出當前的目錄
    print(os.getcwd())

線程

https://www.runoob.com/python/python-multithreading.htmlhtml

import time, threading

def threadtest():
    thread1 = threading.Thread(target=printtime,args=("t1",2));
    thread2 = threading.Thread(target=printtime, args=("t2", 4));
    thread1.start()
    thread2.start()

def printtime(threadname,delay):
    count=0
    while count<5:
        time.sleep(delay)
        count += 1
        print(threadname+":",time.strftime("%a %b %d %H:%M:%S %Y",time.localtime()))

線程同步

若是多個線程共同對某個數據修改,則可能出現不可預料的結果,爲了保證數據的正確性,須要對多個線程進行同步。python

使用Thread對象的Lock和Rlock能夠實現簡單的線程同步,這兩個對象都有acquire方法和release方法,對於那些須要每次只容許一個線程操做的數據,能夠將其操做放到acquire和release方法之間。app

import time, threading

class  myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("Starting " + self.name)
        # 得到鎖,成功得到鎖定後返回True
        # 可選的timeout參數不填時將一直阻塞直到得到鎖定
        # 不然超時後將返回False
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # 釋放鎖
        threadLock.release()

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1
threadLock = threading.Lock()
threads = []
# 建立新線程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 開啓新線程
thread1.start()
thread2.start()
# 添加線程到線程列表
threads.append(thread1)
threads.append(thread2)
# 等待全部線程完成
for t in threads:
    t.join()  # 等待至線程停止。這阻塞調用線程直至線程的join() 方法被調用停止-正常退出或者拋出未處理的異常-或者是可選的超時發生
print("Exiting Main Thread")
相關文章
相關標籤/搜索