我正在Python中制作一个IRC bot。有一个while
循环,每次从IRC服务器收到数据时都会重复循环。我想有另一个while
循环,每分钟运行一次,所以我无法想到将循环合并在一起。两个while循环在一个?
有没有办法“背景”之一的循环,并允许程序的其余部分继续运行,而它“做它的事情”?
我正在Python中制作一个IRC bot。有一个while
循环,每次从IRC服务器收到数据时都会重复循环。我想有另一个while
循环,每分钟运行一次,所以我无法想到将循环合并在一起。两个while循环在一个?
有没有办法“背景”之一的循环,并允许程序的其余部分继续运行,而它“做它的事情”?
这个简单的例子应该让你开始,在这种情况下有两个while循环和time.sleep(seconds)
被用来模仿一些工作
import threading
import time
def func_1():
i = 0
while i<5:
i += 1
time.sleep(1.5) # Do some work for 1.5 seconds
print 'func_1'
def func_2():
i = 0
while i<5:
i += 1
time.sleep(0.5) # Do some work for 0.5 seconds
print 'func_2'
thread1 = threading.Thread(target=func_1)
thread1.start()
thread2 = threading.Thread(target=func_2)
thread2.start()
产地:
func_2 #0.5 seconds elapsed
func_2 #1.0 seconds elapsed
func_1 #1.5 seconds elapsed finally func_1 :)
func_2 #1.5 threading is not mutithreading! ;)
func_2 #2.0 seconds elapsed
func_2 #2.5 seconds elapsed and since variable i is 5 func_2 is no more :(
func_1 #3.0 seconds elapsed
func_1 #4.5 seconds elapsed
func_1 #6.0 seconds elapsed
func_1 #7.5 seconds elapsed
我的意思是threading is not mutithreading! ;)
的意思是,如果您有任何机会认为func_1
和func_2
都被执行了con目前1.5 seconds
它不是真作为线程相同的内存空间中运行,但如果您使用multiprocessing
他们有独立的内存空间,并会同时
最后运行,对于你的情况,你应该使用threading
作为其更适合这些类型的任务
你是什么意思与线程是不是多线程? – Ant
@Ant很好的问题,我主要针对OP *(这不影响这个例子)*做出这个评论,它仅仅意味着'func_1'和'func_2'不会同时运行 –
因此,它们运行线程“几乎同时”,如print(x); print(y)'和多线程,它们实际上是同时运行的?无论如何,线程完美地满足我的需求。 –
听起来像你想使用消息队列? –
你可能想在这里google'python threading'.. –
你说的是'threads'。 – jramirez