在python中实现线程,对不同和相似线程数的不同行为

用户名

我是第一次实现线程。因此,我决定使用一个列表并启动多个线程以查看其工作方式。

这是我运行的代码。

import threading 

    p = [11,22,33,44,55,66,77,88,99,111,222,333,444,555,666,777,888,999,1111,22222,44444,566666,877889528]


    def create_workers():
        for _ in range(1):
            t = threading.Thread(target = work)
            t.daemon  =True
            t.start()

    def work():
        for i in range (0,len(p)):
            print (threading.current_thread().name, p[i])
            p.pop(i)

    if __name__ == '__main__':
        create_workers()

我用多个线程计数运行此代码,每次输出都不同,以某种方式不同,即在线程计数说1和2时,它不会显示列表的所有元素,并且每次运行代码时,我都会得到不同的结果。

这是线程数为1的输出。

Thread-1 11
Thread-1 33
Thread-1 55

我只用1个线程再次运行,这次结果不同

Thread-1 11
Thread-1 33
Thread-1 55
Thread-1 77
Thread-1 99
Thread-1 222
Thread-1 444
Thread-1 666
Thread-1 888
Thread-1 1111
Thread-1 44444

我不确定这种行为,它是如何工作的。类似地,如果我使用4,则结果与我完全相同,所有元素都会显示,并且不再重复。

PmpP。

我想我知道了您想要做的事,主要的缺陷是您认为p的大小对于“工作”函数不会在本地更改,但是它是全局的,因此您从其中删除了元素:

import threading

p = [11,22,33,44,55,66,77,88,99,111,222,333,444,555,666,777,888,999,1111,22222,44444,566666,877889528]

# work the whole list as fast as possible
def work():
    while len(p):
        elem = p.pop(0)
        print (threading.current_thread().name, elem )

# or do same job in parallel n times.
def work_p():
    local_p = list(p)
    while len(local_p):
        elem = local_p.pop(0)
        print (threading.current_thread().name, elem )


class Runner:
    def __init__(self, thread_count):
        self.thr = []
        for _ in range(thread_count):
            t = threading.Thread(target = work)
            t.daemon  = True
            t.start()
            self.thr.append( t )

    def join(self):
        for th in self.thr:
            th.join()


if __name__ == '__main__':
    #use n threads
    Runner(4).join()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章