Low Orbit Flux Logo 2 F

Python - Multithreading

return values from threads??? is that a thing???



import threading

def task1(num):
    print("Cube: {}" .format(num * num * num))

def print_square(num):
    print("Square: {}" .format(num * num))

if __name__ =="__main__":
    t1 = threading.Thread(target=task1, args=(10,))
    t2 = threading.Thread(target=print_cube, args=(10,))

    t1.start()    # start thread
    t2.start()

    # some other work here

    t1.join()   # wait for thread to finish
    t2.join()
    print("Done!")

Note:



os.getpid()                                  # get PID
threading.main_thread()            # get main thread object
threading.main_thread().name  # name of main thread
threading.current_thread().name  # name of current thread



import concurrent.futures

def worker():
    print("Worker thread running")

pool = concurrent.futures.ThreadPoolExecutor(max_workers=2)

pool.submit(worker)   # submit task to thread pool
pool.submit(worker)


# some other work here



pool.shutdown(wait=True)      # wait for worker threads to finish

print("Main thread continuing to run")

”””

”””

Synchronization



import threading 
  
# global variable x 
x = 0
  
def increment(): 
    """ 
    function to increment global variable x 
    """
    global x 
    x += 1
  
def thread_task(lock): 
    """ 
    task for thread 
    calls increment function 100000 times. 
    """
    for _ in range(100000): 
        lock.acquire()        # Lock, blocking set to True by default
        increment() 
        lock.release()         # unlock, ThreadError if already unlocked
  
def main_task(): 
    global x 
    # setting global variable x as 0 
    x = 0
  
    # creating a lock 
    lock = threading.Lock() 
  
    # creating threads 
    t1 = threading.Thread(target=thread_task, args=(lock,)) 
    t2 = threading.Thread(target=thread_task, args=(lock,)) 
  
    # start threads 
    t1.start() 
    t2.start() 
  
    # wait until threads finish their job 
    t1.join() 
    t2.join() 
  
if __name__ == "__main__": 
    for i in range(10): 
        main_task() 
        print("Iteration {0}: x = {1}".format(i,x))