0% found this document useful (0 votes)
5 views2 pages

Parallel Code Walkthrough Guide

This document contains code snippets from 5 different Python programs that use threading. The first code snippet defines a Thread class with init and run methods, creates two thread objects with delays, and runs the threads in parallel. The second snippet finds prime numbers using multiple threads. The third snippet extends the previous code to pass numbers to the Thread class to check primality. The fourth snippet defines a threaded countdown function. The fifth snippet uses a queue to process threads sequentially, printing the factors of numbers.

Uploaded by

Emily
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Parallel Code Walkthrough Guide

This document contains code snippets from 5 different Python programs that use threading. The first code snippet defines a Thread class with init and run methods, creates two thread objects with delays, and runs the threads in parallel. The second snippet finds prime numbers using multiple threads. The third snippet extends the previous code to pass numbers to the Thread class to check primality. The fourth snippet defines a threaded countdown function. The fifth snippet uses a queue to process threads sequentially, printing the factors of numbers.

Uploaded by

Emily
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Emily Mendoza

PDP Quiz
11/17/2022

FIRST CODE
The code in the threading and time modules are being imported to be accessible in the current
code we are [Link] start of the class “MyThread” with the [Link] in the parenthesis
will be what is indexed at the end of the [Link] __init__ function has self, name, and delay as
parameters which will call when using the class. Same as I said before, the
[Link].__init__(self) line will make a thread run when the name of the class is called
with the [Link] = name and [Link] parameters being called. Using the self before the
variables will allow the variable to be used in other functions of the class as well. In the next
function “run” it is saying as the thread is running print out “Starting thread name”, count down
the name and delay of the thread, and print out “Finished thread name”. In this function,
thread_count_down has the parameters of the class name and delay. Function sets a bound of 5
and has the threads count down from 5 using a while loop. This will print the name of the thread
and increment them down. These next two lines are defining thread 1 and 2 and are putting the
variables through the class using the parameters and having the names and a 0.5 sec delay.
Initiating the separate threads and Joins the threads to have them run in parallel. Prints when all
the tasks are actually finished.

SECOND CODE
Importing the square root from the math module, importing _thread and using it as thread in the
code, and importing time. Function is_prime has a parameter of (x). The code is saying if x is
less than 2 print is not a prime number. Else if x is equal to 2 print is a prime number. Else if x is
modulus of 2 and that equals zero than x is not a prime number. Otherwise, set a variable limit
equal to the square root of x plus one in a loop where x in the given range is equal to zero to not
equal a prime number. In the same breath if that modulus is not zero it is a prime number. Next a
set of numbers is made to use in the code. For each number in the set start a new thread and run
is_prime function.

THIRD CODE
First thread will be importing the threading module. This seems to be an addition to the code
right above. The class “MyThread” has a parameter that will be initiating the thread when called.
The __init__ function has the parameters of self and x which are variables that are usable
throughout the class and x will be an input for the class. The run function will start processing as
the class is called. When it runs it will perform the operations to see if the input numbers are
prime numbers. My_input holds the values to be tested and an empty array ‘threads’ is created.
The following loop states that for x values in my_input, make a thread, start running it, and
append that to the threads array. The loop right after that is ensuring that the threads run in
parrellel. Last, when everything is done “finished” will be printed.

FOURTH CODE
This code is importing the modules threading and time. Class myThread will have an input
parameter that starts the thread when called. The _init_ function defines the input parameters of
name and delay. The run function is Starting the thread, locking the said thread and running the
countdown of that thread, and lastly unlocking it so the next thread can run right after. The
function thread_count_down will give both name and display a countdown of 5. The contents
state that while the counter is going down increment from 5 down to 0. While each number is in
play delay for the given time before counting down to the next number. Thread_lock is
referencing the Lock() function outside of the class so it is defined before the run of the class.
Threads 1 and 2 are run with a 0.5 second delay between each count. A runs first then be runs
second.

FIFTH CODE
Importing the modules queue, threading, and time. Class myThread has a parameter that will run
a thread when called. The init function will define the parameter name that will be input for the
class and also be used throughout the class. The run function will start a thread and have other
threads sit in a queue until the first is finished, then exit the current thread to move onto the
queue. Outside of the class is a process_queue function. This function states that while the
function is initiated and true, have x be the thread queued except if the cue is empty. Otherwise
print only the factors that serve as x. The next function print_factors says that using the
parameter of x, the resulting string will print what the positive factors of x are. For the number in
the range of 1 to x if the modulus of the number in the range is equal to 0 than the result string
will be printed. The cariables are then set up and put into the queue. Then Threads A, B, and C
are created using the class. They are started, ran, then done is printed when finished.

Common questions

Powered by AI

Thread synchronization is handled using locks. The 'myThread' class employs a thread lock to prevent concurrent access to critical sections of code, where the lock is acquired before a thread proceeds with the countdown and is released afterward, allowing other threads to run sequentially. The use of locks ensures that no two threads interfere with each other's operations .

The 'run' method in the threads manages the execution logic when a thread starts. In the 'MyThread' class, for example, the 'run' method prints a starting message, performs a countdown using the thread's delay parameter, and then prints a finished message. Importantly, this method enforces order and ensures that threads complete their operations in sequence or parallel, based on the specific implementation .

The countdown implementation in the threading examples serves dual purposes: demonstration of the threading concept and a simple timing delay mechanism to visualize concurrent operations. By counting down from 5, each thread illustrates the concept of execution flow within multi-threading, showing how threads share CPU time. The countdown is synchronized with a delay parameter to stagger execution, making it clear how threads can be managed both sequentially and in parallel .

Using threading for prime number assessment is effective for enhancing computational speed by spreading the workload across multiple CPU cores, allowing concurrent execution of checks. Each number’s prime status is independently assessed within its own thread, minimizing waiting time and better utilizing CPU resources. This approach is particularly beneficial in large datasets where sequential execution would incur significant delays. However, the overhead of creating many threads may outweigh benefits in scenarios with few numbers or minimal computational requirement due to context-switching costs .

The code employs both thread locks and queues to manage concurrency. Threads are initiated to run in parallel by using Python's threading module. However, to prevent conflicts, particular threads use a lock mechanism, ensuring that only one thread can execute a critical section of the code at a time (synchronization). Additionally, when dealing with resources like queues, threads wait for their turn, thereby avoiding race conditions and ensuring orderly execution .

In critical applications, using threading with time delays for execution control can enhance responsiveness and resource utilization. However, potential pitfalls, such as increased complexity and difficulty in debugging race conditions, exist. Furthermore, improper synchronization can lead to data corruption. Delays can also introduce inefficiencies in time-sensitive applications. Therefore, while useful, these mechanisms require careful design to ensure safety, particularly when employed in systems where accuracy and timing are critical .

The '__init__' function in the 'MyThread' class initializes the thread object. It takes parameters self, name, and delay, which allow the thread's name and delay to be used throughout the class. By calling 'threading.Thread.__init__(self)' within __init__, it sets up the necessary threading context so the thread can be started with the specified parameters, thus ensuring that the 'run' method can function as expected .

Prime number checking is integrated into threading by defining a function 'is_prime' which checks if a given number is a prime. For each number in a set, a new thread is started that runs the 'is_prime' function. This setup allows prime checking operations to run concurrently, demonstrating the use of multithreading to parallelize computational tasks and enhance performance by utilizing multiple CPU threads .

The 'print_factors' function, used within a threading context, identifies and prints the positive factors of a number x. When a thread processes through the queue, it executes 'print_factors', thereby utilizing multithreading to handle multiple numbers concurrently. The function runs within threads, showcasing its ability to compute and output results simultaneously rather than sequentially, thus illustrating efficient resource utilization .

Parameters are passed to threads through the '__init__' function of the thread class, which are then accessible throughout the class. This allows dynamic thread configuration, enabling each thread to process unique data, such as names, delays, or numbers for processing, which influences their operations. This parameterization is significant as it supports custom thread behavior, allows specific delay timings, and enables input-specific processing tasks within threads .

You might also like