您的位置:首页 > 编程语言 > Python开发

python:线程的使用、线程共享全局变量、列表作为参数(全局变量)、避免全局变量被修改

2017-07-18 18:38 816 查看
进程是资源分布的单元

线程是进程中真正执行代码的

进程运行起来,会有一个主线程进行运行 

父子线程:相互独立运行,当所有的子线程执行完后,主线程才执行完

下面这个程序就是一个线程

#线程也是python实现多任务的一种方式,thread模块是比较底层的模块
#threading模块是对thread做了一些包装,更方便使用
#多线程的执行
import threading
import time

def sayHello():#多个线程去执行一个函数,完全可以
print("hello")
time.sleep(2)

if __name__=="__main__":
for i in range(5):
t=threading.Thread(target=sayHello)#同时执行,而不是一个一个执行
t.start()#创建一个新的线程,去target中执行,这里开启 了5个线程

'''
hello
hello
hello
hello
hello
'''


创建线程的另外一种方式:

import threading
import time

class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg="I'm" +self.name+'@'+str(i) #name属性中保存的是当前线程的名字
print(msg)

if __name__=='__main__':
t=MyThread()#实例化类的对象就可以调用
t.start()

'''
I'mThread-1@0
I'mThread-1@1
I'mThread-1@2
'''

父子进程和父子线程的执行顺序不一定,由操作系统的调度算法决定

线程共享全局变量,进程不是
import threading
from threading import Thread
import time

thnum=100

class MyThread(threading.Thread):
def run(self):
for i in range(3):
global thnum
thnum+=100
time.sleep(1)
msg="I'm" +self.name+'@'+str(i) #name属性中保存的是当前线程的名字
print(msg)
print(thnum)

def test():
global thnum
print(thnum)
if __name__=='__main__':
t=MyThread()
t.start()

time.sleep(4)#保证第一个线程执行完
thn=Thread(target=test)
thn.start()

'''
I'mThread-1@0
200
I'mThread-1@1
300
I'mThread-1@2
400
400
'''

线程使用全局变量的弊端,一旦设置不好时间,则输出错误的结果
import threading
from threading import Thread
import time

thnum=0

class MyThread(threading.Thread):
def run(self):
for i in range(10000):
global thnum
thnum+=1
print(thnum)

def test():
global thnum
for i in range(10000):
thnum+=1
print(thnum)
if __name__=='__main__':
t=MyThread()
t.start()

time.sleep(4)#保证第一个线程执行完,这样的话运行结果为20000
#但是如果将这句话屏蔽掉的话,就会发现结果不是20000,全局变量的值在其中有交叉,而不是先运行完第一个程序再运行第二个程序
thn=Thread(target=test)
thn.start()

'''
I'mThread-1@0
200
I'mThread-1@1
300
I'mThread-1@2
400
400
'''

列表当做参数传递给线程,会当做全局变量
import threading
from threading import Thread
import time

thnum=[11,22,33,44]

class MyThread(threading.Thread):
def run(self):
for i in range(3):
thnum.append(i)
print(thnum)

def test():
print(thnum)
if __name__=='__main__':
t=MyThread()
t.start()

time.sleep(1)#保证第一个线程执行完
thn=Thread(target=test)
thn.start()

'''
[11, 22, 33, 44, 0, 1, 2]
[11, 22, 33, 44, 0, 1, 2]

'''

避免全局变量被修改:
import threading
from threading import Thread
import time

thnum=0
f_flag=0

class MyThread(threading.Thread):
def run(self):
for i in range(10000):
global thnum
thnum+=1
global f_flag
f_flag=1
print(thnum)

def test():
global thnum#下面的f_flag是全局变量,但是这里没有进行修改,所有不用加global
while True:
if f_flag!=0:
for i in range(10000):
thnum+=1
break

print(thnum)
if __name__=='__main__':
t=MyThread()
t.start()

time.sleep(4)#保证第一个线程执行完,这样的话运行结果为20000
#但是如果将这句话屏蔽掉的话,就会发现结果不是20000,全局变量的值在其中有交叉,而不是先运行完第一个程序再运行第二个程序
thn=Thread(target=test)
thn.start()

'''
10000
20000
'''
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐