一、多线程实例
线程时应用程序中工作的最小单位,python中提供了threading模块来对多线程操作,一般多核cpu采用多进程方式,单核才采用多线程方式
方法:
将要执行的方法threading.Thread作为参数传给构造方法(和多进程类似),格式如下:
t = threading.Thread(target=action,args=(i,))
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import
threading
def
worker(n):
print
(
"start worker{0}"
.
format
(n))
class
Mythread(threading.Thread):
def
__init__(
self
,args):
super
(Mythread,
self
).__init__()
# super(Mythread,self)超类,将类接收到的参数threading.Thread,传给构造函数,最后赋值给self.args,便于类中其他函数调用
self
.args
=
args
def
run(
self
):
print
(
"start Mythread {0}"
.
format
(
self
.args))
if
__name__
=
=
"__main__"
:
for
i
in
range
(
1
,
6
):
t1
=
threading.Thread(target
=
worker,args
=
(i,))
t1.start()
t1.join()
for
x
in
range
(
6
,
11
):
t2
=
Mythread(x)
t2.start()
t2.join()
|
运行结果:
start worker1
start worker2
start worker3
start worker4
start worker5
start Mythread 6
start Mythread 7
start Mythread 8
start Mythread 9
start Mythread 10
扩展:super()方法的语法: super(type[, object-or-type]);type -- 类名,object-or-type --对象或类型,一般为self
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
class
Parent(
object
):
def
__init__(
self
):
self
.parent
=
"Good"
print
(
'Parent'
)
def
identity(
self
, message):
print
(
"%s I'm parent"
%
message)
class
Child(Parent):
def
__init__(
self
):
super
(Child,
self
).__init__()
#首先找到Child的父类(Parent),然后把类Child的对象转换为类Parent的对象,调用父类的构造函数__init__()
print
(
'Child'
)
print
(
"******"
*
4
)
def
identity(
self
, message):
super
(Child,
self
).identity(message)
#首先找到Child的父类(Parent),然后把类Child的对象转换为类Parent的对象,调用父类的identity(message)函数
print
(
"I'm child"
)
print
(
"******"
*
4
)
print
(
self
.parent)
if
__name__
=
=
'__main__'
:
Test
=
Child()
Test.identity(
'hello China'
)
|
运行结果:
Parent
Child
************************
hello China I'm parent
I'm child
************************
Good
二、线程锁
通过threading.Lock()来创建锁,函数在执行前先获得锁,执行后释放锁,和进程锁相似
with lock:
或者
lock.acquire() #先获得锁
...
lock.release() #执行完,释放锁
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import
threading
import
time
def
worker(name,lock):
with lock:
print
(
"start {0}"
.
format
(name))
time.sleep(
3
)
print
(
"end {0}"
.
format
(name))
if
__name__
=
=
"__main__"
:
lock
=
threading.Lock()
t1
=
threading.Thread(target
=
worker,args
=
(
"worker1"
,lock))
t2
=
threading.Thread(target
=
worker,args
=
(
"worker2"
, lock))
t1.start()
t2.start()
print
(
"main end"
)
|
运行结果:
start worker1
main end
end worker1
start worker2
end worker2
说明:只有线程1结束以后,线程2才能执行
三、线程共享变量
多线程和多进程不同之处在于多线程本身就是可以和父进程进行共享内存的,这也是为什么其中一个线程挂掉之后,其他线程也死掉的原因
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
threading
def
worker(l):
l.append(
"hello"
)
l.append(
"china"
)
l.append(
"world"
)
if
__name__
=
=
"__main__"
:
l
=
list
()
l
+
=
range
(
1
,
5
)
print
(l)
t
=
threading.Thread(target
=
worker,args
=
(l,))
t.start()
print
(l)
|
运行结果:
[1, 2, 3, 4]
[1, 2, 3, 4, 'hello', 'china', 'world']