Run two calls to a function simultaneously with this threading @background decorator.
An example of a threading background decorator (Python)
''' threading_run_background_deco2.py
apply threading to a function with a function decorator
to allow it to run in the background
tested with Python27 and Python33 by vegaseat 27jun2014
'''
import time
import threading
def background(f):
'''
a threading decorator
use @background above the function you want to run in the background
'''
def bg_f(*a, **kw):
threading.Thread(target=f, args=a, kwargs=kw).start()
return bg_f
@background
def counter(name, n):
"""show the count every second"""
for k in range(1, n+1):
print("{} counts {}".format(name, k))
time.sleep(1)
# start the counters
# note that with the @background decorator
# Frank and Doris count simultaneously
# note from SOS: Frank may not always count first
counter("Frank", 5)
counter("Doris", 5)
'''
result with the @background decorator ...
Frank counts 1
Doris counts 1
Frank counts 2
Doris counts 2
Frank counts 3
Doris counts 3
Frank counts 4
Doris counts 4
Frank counts 5
Doris counts 5
result without the @background decorator ...
Frank counts 1
Frank counts 2
Frank counts 3
Frank counts 4
Frank counts 5
Doris counts 1
Doris counts 2
Doris counts 3
Doris counts 4
Doris counts 5
'''
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
chriswelborn 63 ...
HiHe 174 Junior Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
chriswelborn 63 ...
HiHe 174 Junior Poster
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
HiHe 174 Junior Poster
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
HiHe 174 Junior Poster
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster
HiHe 174 Junior Poster
snippsat 661 Master Poster
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Lardmeister 461 Posting Virtuoso
Lardmeister 461 Posting Virtuoso
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.