Answers for "multithreading python"

5

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")
Posted by: Guest on June-27-2020
14

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()
Posted by: Guest on December-05-2020
5

multithreading in python

from multiprocessing.pool import ThreadPool

def stringFunction(value):
    my_str = 3 + value
    return my_str


def stringFunctio(value):
    my_str = 33 + value
    return my_str



pool = ThreadPool(processes=1)

    
thread1 = pool.apply_async(stringFunction,(8,))
thread2 = pool.apply_async(stringFunctio,(8,))

return_val = thread1.get()
return_val1 = thread2.get()
Posted by: Guest on February-23-2021
4

python 2.7 multithreading

from multiprocessing.pool import ThreadPool as Pool

pool_size = 10
pool = Pool(pool_size)

results = []

for region, directory_ids in direct_dict.iteritems():
    for dir in directory_ids:
        result = pool.apply_async(describe_with_directory_workspaces,
                                  (region, dir, username))
        results.append(result)

for result in results:
    code, content = result.get()
    if code == 0:
        # ...
Posted by: Guest on February-10-2021

Python Answers by Framework

Browse Popular Code Answers by Language