这是我的代码:为什么我的多线程代码,花更多的时间比单线程代码
import re,threading
class key_value:
def __init__(self,filename='a.txt'):
self.filename = filename
def __getitem__(self,key):
file = open(self.filename,'r')
data = file.read()
value = re.findall(r''+str(key)+' - (\S+)',data)
return value
def __setitem__(self,key,value):
data = open(self.filename).read()
b = re.split(r'('+str(key)+' -)\S*', data)
#
if len(b) == 1:
result = str(key)+' - '+str(value)
result += '\n'
file = open(self.filename,'a')
file.write(result)
return
elif type(value) == type([]):
result = "".join(str(x) + value.pop(0) if x == str(key)+' - ' else x for x in b)
else :
result = "".join(str(x) + str(value) if str(x) == str(key)+' - ' else x for x in b)
file = open(self.filename,'w')
file.write(result)
def run(self):
print 'the thread is running!!'
class do_thread(threading.Thread):
def __init__(self,filename='a.txt',key=None,value=None):
threading.Thread.__init__(self)
self.filename = filename
self.key=key
self.value=value
def run(self):
print 'the thread is running!!'
a = key_value(self.filename)
if(self.key and self.value):
a[self.key] = self.value
elif(self.key):
self.value = a[self.key]
#'''#Multi-threading code
for i in range(1000):
a = do_thread(key=i,value=i)
#print 'the main programme'
a.start()
#a.join()
#print 'game over'
'''# Single-threaded code
for i in range(1000):
a = key_value()
a[i] = i
'''
我的老板告诉我要多线程添加到我的代码,
我添加它,但我觉得多线程花费更多的时间,
究竟什么是有用的多线程,我的老板说的,
感谢
您是否在多核计算机上试过了? – BenjaminB 2011-03-19 14:38:27
不,我的电脑是单核的 – zjm1126 2011-03-19 14:42:37
您正在产生1000个线程,并且启动一个线程会产生一些开销。线程为您提供了并行性,但不会自动让事情变得更快。在你的例子中,他们都在同一时间写入同一个文件,这不可能是你想要的。 – samplebias 2011-03-19 14:43:07