Python入门-多线程

本文介绍Python的多线程:

1、使用_thread模块

import _thread
import time

def print_time(threadName,delay):
    count=1;
    while count<5:
        time.sleep(delay)
        count+=1
        print(threadName+time.ctime(time.time()))
    
try:
    _thread.start_new_thread(print_time,("thread-1",2))
    _thread.start_new_thread(print_time,("thread-2",4))
except Exception as e:
    print("错误"+str(e))

while 1:
    pass    #空语句

2、使用threading模块

import threading
import time

def print_time(threadName,delay):
    count=1;
    while count<5:
        time.sleep(delay)
        count+=1
        print(threadName+time.ctime(time.time()))

class myThread(threading.Thread):    #继承Thread类,并重写run方法
    threadId1=0
    name1=""
    def __init__(self,threadId,name):
        threading.Thread.__init__(self)   #调用父类
        self.threadId1=threadId
        self.name1=name
        return

    def run(self):
        print("开始线程"+self.name1)
        print_time(self.name1,2)
        print("结束线程"+self.name1)

t1=myThread(1,"t1")
t2=myThread(2,"t2")
t1.start()
t2.start()
t1.join()
t2.join()
while 1:
    pass

3、线程同步问题

import threading
import time

myList=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
class MyThread(threading.Thread):
    threadName=''
    flag=0   # 0表示做读,1表示做写1
    threadLock=threading.Lock()   #获取锁的对象
    def __init__(self,threadName,flag):
        threading.Thread.__init__(self)  # 调用父类
        self.threadName=threadName
        self.flag=flag

    def run(self):
        print("线程开始"+self.threadName)
        MyThread.threadLock.acquire()    #获取锁
        MyThread.change(self,self.threadName,self.flag)
        MyThread.threadLock.release()    #释放锁
        print("线程结束"+self.threadName)

    def change(self,threadName,flag):
        if flag==0:
            for a in myList:  #读操作
                print(a)
                time.sleep(1)
        elif flag==1:
            co=0
            while co<len(myList):  #不断地把0变为1
                myList[co]=1
                #print(myList[co])
                time.sleep(1)
                co+=1

tMy1=MyThread("t1",0)   #做读操作
tMy2=MyThread("t2",1)   #做写操作
tMy1.start()
tMy2.start()
tMy1.join()
tMy2.join()

说明:线程tMy1去读List,线程tMy2去把List的内容改为1,;

当注释掉“获取锁”和“释放锁”的代码时,可以看到,tMy1读出了1,;当不注释,必须先读完才能再去修改

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值