multithreading
//Bless anyone who decides to follow this path
multithreading
//Bless anyone who decides to follow this path
what is multithreading
Multithreading is a model of program execution
that allows for multiple threads to be created
within a process, executing independently but
concurrently sharing process resources.
Depending on the hardware, threads can run
fully parallel if they are distributed to their own CPU core.
how to do multithreading
import threading
def func1():
# your function
def func2():
# your function
if __name__ == '__main__':
threading.Thread(target=func1).start()
threading.Thread(target=func2).start()
multithreading in java
class Count implements Runnable
{
Thread mythread ;
Count()
{
mythread = new Thread(this, "my runnable thread");
System.out.println("my thread created" + mythread);
mythread.start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("mythread run is over" );
}
}
class RunnableExample
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.mythread.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread run is over" );
}
}
multithreading
import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(2)
logging.info("Thread %s: finishing", name)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
threads = list()
for index in range(3):
logging.info("Main : create and start thread %d.", index)
x = threading.Thread(target=thread_function, args=(index,))
threads.append(x)
x.start()
for index, thread in enumerate(threads):
logging.info("Main : before joining thread %d.", index)
thread.join()
logging.info("Main : thread %d done", index)
multithreading
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=2)
thread1 = pool.apply_async(stringFunction,(8,))
thread2 = pool.apply_async(stringFunctio,(8,))
return_val = thread1.get()
return_val1 = thread2.get()
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us