Difference between revisions of "Python threading"
From Noah.org
Jump to navigationJump to search (New page: Category:Engineering Category:Python == Basic threading example == <pre> import time import threading class roller (threading.Thread): def __init__(self, interval, function,...) |
|||
Line 2: | Line 2: | ||
[[Category:Python]] | [[Category:Python]] | ||
== Basic threading example == | == Basic threading example == | ||
+ | |||
+ | This runs my_function in a thread loop. | ||
+ | Note that you might see "Done!" before the last line of thread output. | ||
+ | Welcome to threadland! | ||
<pre> | <pre> | ||
+ | #!/usr/bin/env python | ||
+ | |||
import time | import time | ||
import threading | import threading | ||
+ | |||
class roller (threading.Thread): | class roller (threading.Thread): | ||
def __init__(self, interval, function, args=[], kwargs={}): | def __init__(self, interval, function, args=[], kwargs={}): | ||
Line 15: | Line 22: | ||
self.finished = threading.Event() | self.finished = threading.Event() | ||
def cancel(self): | def cancel(self): | ||
− | |||
self.finished.set() | self.finished.set() | ||
def run(self): | def run(self): | ||
Line 22: | Line 28: | ||
self.function(*self.args, **self.kwargs) | self.function(*self.args, **self.kwargs) | ||
− | r = roller (0. | + | def my_function (a, b, c): |
+ | print "meaningless arguments as an example:", a, b, c | ||
+ | print time.asctime() | ||
+ | |||
+ | print "Calling my_function() in a thread every 1/10th of second for two seconds." | ||
+ | r = roller (0.1, my_function, (1,0,-1)) | ||
r.start() | r.start() | ||
− | time.sleep( | + | time.sleep(2) |
r.cancel() | r.cancel() | ||
+ | print "Done!" | ||
</pre> | </pre> |
Revision as of 13:32, 7 June 2007
Basic threading example
This runs my_function in a thread loop. Note that you might see "Done!" before the last line of thread output. Welcome to threadland!
#!/usr/bin/env python import time import threading class roller (threading.Thread): def __init__(self, interval, function, args=[], kwargs={}): threading.Thread.__init__(self) self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.finished = threading.Event() def cancel(self): self.finished.set() def run(self): while not self.finished.isSet(): self.finished.wait(self.interval) self.function(*self.args, **self.kwargs) def my_function (a, b, c): print "meaningless arguments as an example:", a, b, c print time.asctime() print "Calling my_function() in a thread every 1/10th of second for two seconds." r = roller (0.1, my_function, (1,0,-1)) r.start() time.sleep(2) r.cancel() print "Done!"