为什么我的多线程代码比单线程代码花费更多的时间 [英] why my Multi-threading code spend More time than Single-threading code

查看:82
本文介绍了为什么我的多线程代码比单线程代码花费更多的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

'''

我的老板告诉我在代码中添加多线程,

my boss told me to add Multi-threading to my code ,

我添加了它,但是我发现多线程花费更多的时间,

i add it , but i find the Multi-threading spend more time ,

那么老板说的多线程有什么用呢?

so what is the useful of the Multi-threading that my boss said ,

谢谢

推荐答案

CPython(主要的Python实现)不是多线程的. GIL 造成了麻烦.因此,您只有两个线程在一个内核上运行(即它们不是并行运行的),但是在所有上下文切换和其他开销的情况下,线程必然具有.不过请注意:

CPython (the main Python implementation) doesn't multi-thread. The GIL gets in the way. So you just have two threads running on one core (i.e. they don't run in parallel) but with all the context switching and other overhead a thread necesarily has. Note though:

  • 即使您使用多线程,也仍然受到内核数量的限制.一台双核计算机只能同时执行两次计算,无论它们是在两个内核之间共享还是在一个内核上运行,启动一千个线程都不会改变这种情况.
  • 但是,例如,运行多于核心的线程仍然有用.做大量的I/O-CPU在等待I/O完成时处于空闲状态,因此您不受CPU时间的限制.

从评论看来,您的计算机仍然无法进行多线程处理.好吧,以上仍然成立.

From the comments it seems your computer is incapable of multi-threading anyway. Well, the above still holds.

这篇关于为什么我的多线程代码比单线程代码花费更多的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆