python thread function code example
Example 1: create new thread python
from threading import Thread
from time import sleep
def threaded_function(arg):
for i in range(arg):
print("running")
sleep(1)
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
print("thread finished...exiting")
Example 2: threading python example
# A minimal threading example with function calls
import threading
import time
def loop1_10():
for i in range(1, 11):
time.sleep(1)
print(i)
threading.Thread(target=loop1_10).start()
# A minimal threading example with an object
import threading
import time
class MyThread(threading.Thread):
def run(self): # Default called function with mythread.start()
print("{} started!".format(self.getName())) # "Thread-x started!"
time.sleep(1) # Pretend to work for a second
print("{} finished!".format(self.getName())) # "Thread-x finished!"
def main():
for x in range(4): # Four times...
mythread = MyThread(name = "Thread-{}".format(x)) # ...Instantiate a thread and pass a unique ID to it
mythread.start() # ...Start the thread, run method will be invoked
time.sleep(.9) # ...Wait 0.9 seconds before starting another
if __name__ == '__main__':
main()
Example 3: python thread function
x = threading.Thread(target=thread_function, args=(1,), daemon=True)
x.start()
# x.join()
Example 4: how to thread python
import threading, time
def worker():
"""thread worker function"""
print('Worker')
return
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
print('Thread')
Example 5: how to run same function on multiple threads in pyhton
import multiprocessing
def worker(num):
""" Worker procedure
"""
print('Worker:', str(num))
# Mind the "if" instruction!
if __name__ == '__main__':
jobs = [] # list of jobs
jobs_num = 5 # number of workers
for i in range(jobs_num):
# Declare a new process and pass arguments to it
p1 = multiprocessing.Process(target=worker, args=(i,))
jobs.append(p1)
# Declare a new process and pass arguments to it
p2 = multiprocessing.Process(target=worker, args=(i+10,))
jobs.append(p2)
p1.start() # starting workers
p2.start() # starting workers