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!
Very 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.html

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()))

线程同步

如果多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步。

使用Thread对象的Lock和Rlock可以实现简单的线程同步,这两个对象都有acquire方法和release方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到acquire和release方法之间。

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")



原文地址:https://www.cnblogs.com/shaner/p/7887103.html