1.线程共享变量
多线程和多进程不同之处在于,多线程本身就是可以和父线程共享内存的,这也是为什么其中一个线程挂掉以后,为什么其他线程也会死掉的道理。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import
threading
def
worker(l):
l.append(
"li"
)
l.append(
"and"
)
l.append(
"lou"
)
if
__name__
=
=
"__main__"
:
l
=
[]
l
+
=
range
(
1
,
10
)
print
(l)
t
=
threading.Thread(target
=
worker, args
=
(l,))
t.start()
print
(l)
|
返回结果:
1
2
|
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
]
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
'li'
,
'and'
,
'lou'
]
|
2.线程池(扩展内容,了解即可)
通过传入一个参数组来实现多线程,并且它的多线程是有序的,顺序与参数组中的参数顺序保持一致。
安装包:
pip install threadpool
调用格式:
1
2
3
4
5
|
from
threadpool
import
*
pool
=
TreadPool(poolsize)
requests
=
makeRequests(some_callable, list_of_args, callback)
[pool.putRequest(req)
for
req
in
requests]
pool.wait()
|
举例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import
threadpool
def
hello(m, n, o):
print
(
"m = {0}, n = {1}, o = {2}"
.
format
(m, n, o))
if
__name__
=
=
"__main__"
:
#方法一:
lst_vars_1
=
[
'1'
,
'2'
,
'3'
]
lst_vars_2
=
[
'4'
,
'5'
,
'6'
]
func_var
=
[(lst_vars_1,
None
), (lst_vars_2,
None
)]
#方法二:
dict_vars_1
=
{
'm'
:
'1'
,
'n'
:
'2'
,
'o'
:
'3'
}
dict_vars_2
=
{
'm'
:
'4'
,
'n'
:
'5'
,
'o'
:
'6'
}
func_var
=
[(
None
, dict_vars_1), (
None
, dict_vars_2)]
pool
=
threadpool.ThreadPool(
2
)
requests
=
threadpool.makeRequests(hello, func_var)
[pool.putRequest(req)
for
req
in
requests]
pool.wait()
|
返回结果:
1
2
|
m
=
1
, n
=
2
, o
=
3
m
=
4
, n
=
5
, o
=
6
|
本文转自 听丶飞鸟说 51CTO博客,原文链接:http://blog.51cto.com/286577399/2050860