mon02_day08

day08/thread1.py
"""
thread1.py  线程创建
步骤: 1. 封装线程函数
      2. 创建线程对象
      3. 启动线程
      4. 回收线程
"""

import threading
from time import sleep
import os

a = 1

# 线程函数
def music():
    for i in range(3):
        sleep(2)
        print(os.getpid(),"播放:我和我的祖国")
    global a
    print("a = ",a)
    a = 10000

# 创建线程对象
t = threading.Thread(target=music)
t.start() # 启动线程

for i in range(2):
    sleep(4)
    print(os.getpid(),"播放:五星红旗")

t.join() # 回收线程

print("a:",a)

"""
thread2.py  线程函数传参
"""

from threading import Thread
from time import sleep

# 含有参数线程函数
def fun(sec,name):
    print("线程函数参数")
    sleep(sec)
    print("%s执行完成"%name)

# 创建多个线程
jobs = []

# 创建5个线程
for i in range(5):
    t = Thread(target=fun,args=(2,),
               kwargs={'name':'T%d'%i})
    jobs.append(t)
    t.start()

for i in jobs:
    i.join()

"""
线程属性说明thread_attr.py
"""
from threading import Thread
from time import sleep

def fun():
    print("============")
    sleep(3)
    print("线程属性测试")

t = Thread(target = fun)

t.setDaemon(True) # 主线程退出分支线程也退出

t.start()

print("Name:",t.getName()) # 线程名称
print("is Alive:",t.is_alive()) # 是否在生命中期
print("daemon:",t.isDaemon()) # daemon属性值


day7/myThread.py
from threading import Thread
from time import sleep,ctime

class MyThread(Thread):
    def __init__(self,target=None,args=(),kwargs={}):
        super().__init__()
        self.target = target
        self.args = args
        self.kwargs = kwargs

    def run(self):
        self.target(*self.args,**self.kwargs)


####################################################
def player(sec,song):
    for i in range(3):
        print("Playing %s: %s"%(song,ctime()))
        sleep(sec)

t = MyThread(target = player,args=(3,),
             kwargs={'song':'凉凉'})
t.start()
t.join()

day8/thread_event.py
"""
Event 互斥方法
"""

from threading import Thread,Event

s = None # 用于通信
e = Event() # event对象

def 杨子荣():
    print("杨子荣前来拜山头")
    global s
    s = "天王盖地虎"
    e.set() # 解除wait阻塞

t = Thread(target=杨子荣)
t.start()
print("说对口令就是自己人")
e.wait() # 阻塞等待说口令
if s == '天王盖地虎':
    print("宝塔镇河妖")
    print("确认过眼神,你是对的人")
else:
    print("打死他....")

t.join()




day8/thread_lock.py
"""
lock 互斥方法演示
"""

from threading import Thread,Lock

a = b = 0
lock = Lock() # 线程锁

def value():
    while True:
        lock.acquire()  # 上锁
        if a != b:
            print("a = %d,b = %d"%(a,b))
        lock.release()  # 解锁

t = Thread(target=value)
t.start()

while True:
    with lock:  # 上锁
        a += 1
        b += 1
                # 自动解锁

t.join()



day8/dead_lock.py
from time import sleep
from threading import Thread,Lock

# 账户类
class Account:
    def __init__(self,id,balance,lock):
        self.id = id   # 账户名
        self.balance = balance # 存款
        self.lock = lock #

    # 取钱
    def withdraw(self,amount):
        self.balance -= amount

    # 存钱
    def deposit(self,amount):
        self.balance += amount

    # 查看余额
    def get_balance(self):
        return self.balance

# 两个账户
Tom = Account('Tom',5000,Lock())
Alex = Account('Alex',8000,Lock())

# 转账
def transfer(from_,to,amount):
    if from_.lock.acquire():
        from_.withdraw(amount) # from_钱减少
        sleep(0.1)
        # 两个线程都阻塞在to上锁位置
        if to.lock.acquire():
            to.deposit(amount) # to 钱增加
            to.lock.release()
        from_.lock.release()
    print("%s给%s转了%d"%(from_.id,to.id,amount))

t1 = Thread(target = transfer,args=(Tom,Alex,2000))
t2 = Thread(target = transfer,args=(Alex,Tom,1800))
t1.start()
t2.start()
t1.join()
t2.join()





"""
exc1
使用多个线程从不同的地方拷贝一个文件
每个线程负责拷贝文件的一部分
"""
from threading import Thread
import os

urls = ["/home/tarena/桌面/",
        "/home/tarena/文档/",
        "/home/tarena/图片/",
        "/home/tarena/下载/",
        "/home/tarena/视频/",
        "/home/tarena/音乐/"
]

# 输入要下载的文件,判断urls列表中哪些地方有这个文件
# os.path.exists()
filename = input("要下载的文件:")
exp = []  # 存放有该文件的路径
for i in urls:
    if os.path.exists(i+filename):
        exp.append(i+filename)
path_num = len(exp) # 表示一共有几处可以拷贝

if path_num == 0:
    print("没有资源")
    os._exit(0)

# 获取文件大小,确定每个线程下载多少
file_size = os.path.getsize(exp[0])
block_size = file_size // path_num + 1

# 创建若干线程,每个线程拷贝一部分,拷贝过程封装为线程函数
def load(path,num):
    # path: 从哪个路径拷贝
    # num:拷贝的是第几块
    fw = open(str(num)+filename,'wb')
    f = open(path,'rb')
    f.seek(block_size*(num - 1),0)
    n = block_size
    while True:
        if n < 1024:
            data = f.read(n)
            fw.write(data)
            break
        else:
            data = f.read(1024)
            fw.write(data)
            n -= 1024
    fw.close()
    f.close()

num = 1
jobs = []
for path in exp:
    t = Thread(target=load,args=(path,num))
    jobs.append(t)
    t.start()
    num += 1

for i in jobs:
    i.join()

# 将多个文件拼接到一起
fw = open(filename,'wb')
for i in range(1,path_num+1):
    f = open(str(i)+filename,'rb')
    while True:
        data = f.read(1024)
        if not data:
            break
        fw.write(data)
    os.remove(str(i)+filename)

"""
使用多个线程从不同的地方拷贝一个文件
每个线程负责拷贝文件的一部分
"""
from threading import Thread,Lock
import os
from time import sleep

urls = ["/home/tarena/桌面/",
        "/home/tarena/文档/",
        "/home/tarena/图片/",
        "/home/tarena/下载/",
        "/home/tarena/视频/",
        "/home/tarena/音乐/"
]

lock = Lock() #

# 输入要下载的文件,判断urls列表中哪些地方有这个文件
# os.path.exists()
filename = input("要下载的文件:")
exp = []  # 存放有该文件的路径
for i in urls:
    if os.path.exists(i+filename):
        exp.append(i+filename)
path_num = len(exp) # 表示一共有几处可以拷贝

if path_num == 0:
    print("没有资源")
    os._exit(0)

# 获取文件大小,确定每个线程下载多少
file_size = os.path.getsize(exp[0])
block_size = file_size // path_num + 1

# 创建若干线程,每个线程拷贝一部分,拷贝过程封装为线程函数
fw = open(filename, 'wb')

def load(path,num):
    # path: 从哪个路径拷贝
    # num:拷贝的是第几块
    f = open(path,'rb')
    f.seek(block_size*(num - 1),0)
    data = f.read(block_size)

    with lock:
        fw.seek(block_size*(num - 1),0)
        sleep(0.1)
        fw.write(data)

    f.close()

num = 1
jobs = []
for path in exp:
    t = Thread(target=load,args=(path,num))
    jobs.append(t)
    t.start()
    num += 1

for i in jobs:
    i.join()



"""
测试用例
"""

# 计算
def count(x,y):
    c = 0
    while c < 7000000:
        x += 1
        y += 1
        c += 1

# io
def io():
    write()
    read()

def write():
    f = open('test','w')
    for i in range(1800000):
        f.write("Hello world\n")
    f.close()

def read():
    f = open('test')
    lines = f.readlines()
    f.close()

 

猜你喜欢

转载自www.cnblogs.com/xiaoliangliu86/p/11657717.html