python threading start function code example
Example 1: threading python example
import threading
import time
def loop1_10():
for i in range(1, 11):
time.sleep(1)
print(i)
threading.Thread(target=loop1_10).start()
import threading
import time
class MyThread(threading.Thread):
def run(self):
print("{} started!".format(self.getName()))
time.sleep(1)
print("{} finished!".format(self.getName()))
def main():
for x in range(4):
mythread = MyThread(name = "Thread-{}".format(x))
mythread.start()
time.sleep(.9)
if __name__ == '__main__':
main()
Example 2: launch a script from python using threading
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, 5, self.counter)
print "Exiting " + self.name
def print_time(threadName, counter, delay):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
thread1.start()
thread2.start()
print "Exiting Main Thread"