最后写一个例子 , 也就是 引发我学习多线程的原因。
我接到一个任务 ,大约三十万的数据量,一大堆数据库查询之后,最后需要把一组数插入数据库。
我使用单线程的写完了, 可以跑起来大概需要10个小时。 于是,我知道我学习多线程的机会来了。
那个程序,后来我用多进程完成了。 现在想用多线程再实现一遍。

任务,source.txt内有30W的数字,从0-299999。 需要用多线程,把这30W的数,写到10个文件中去。

我将之前的程序,稍微改了一下, 下面是代码:

#coding:utf8


import threading,random
import time

class Cut(threading.Thread):
def __init__(self,content, i):
threading.Thread.__init__(self)
self.content = content
self.index = i


def run(self):
global alock
f = open("target_%s" % self.index, "w")

while True:
alock.acquire()
length = len(content)
if length >0:
tmp = content.pop()
alock.release()
else:
alock.release()
break

f.write("%s\n" % tmp)
print self.getName(), tmp
f.close()


if '__main__' == __name__:

filename = "source.txt"
f = open(filename)
content = f.read().split("\n")
content = content[:-1]

global alock
alock = threading.Lock()

for i in range(10):
workman = Cut(content, i)
workman.start()

f.close()

下面是我的运行结果,经过验证,生成的10个文件中的内容,没有重复,也没有遗漏。 达到预期。

[root@2.8.4.100 thread]# ll
总用量 9748
-rw-r--r-- 1 root root 20 11月 30 21:53 easy.txt
-rw-r--r-- 1 root root 89 11月 30 18:37 makefile.py
-rw-r--r-- 1 root root 1988890 12月 1 16:15 ret
-rw-r--r-- 1 root root 1988890 12月 1 16:16 ret2
-rw-r--r-- 1 root root 1988890 12月 1 16:17 ret3
-rw-r--r-- 1 root root 1988890 11月 30 18:37 source.txt
-rw-r--r-- 1 root root 206096 12月 1 16:14 target_0
-rw-r--r-- 1 root root 201954 12月 1 16:14 target_1
-rw-r--r-- 1 root root 202109 12月 1 16:14 target_2
-rw-r--r-- 1 root root 198264 12月 1 16:14 target_3
-rw-r--r-- 1 root root 192243 12月 1 16:14 target_4
-rw-r--r-- 1 root root 201707 12月 1 16:14 target_5
-rw-r--r-- 1 root root 199353 12月 1 16:14 target_6
-rw-r--r-- 1 root root 188272 12月 1 16:14 target_7
-rw-r--r-- 1 root root 194191 12月 1 16:14 target_8
-rw-r--r-- 1 root root 204701 12月 1 16:14 target_9
-rw-r--r-- 1 root root 953 12月 1 16:14 work.py
[root@2.8.4.100 thread]#

​https://docs.python.org/2/library/threading.html​​​
这个网页中还有 条件, 信号等别的同步的模块,怎么都不用啊, 怎么说呢
就像你去了一家饭店,饭店有几十道菜,不能说,你不把这些菜全吃过就饱不了。
何况还有那么多东西需要学习
以后再说吧