Single/Multi Dimensional matrix operations using multi threading in Python.

Ahip Sharma
9 min readDec 6, 2022

Adding or subtracting or multiplication or Division of matrices takes O(n²) time without threads, but using threads does not reduce the time complexity of the program. For achieving we split the task into cores as if there were 4 cores, split matrix part and split matrix computation into 4 parts, each core taking over one of the operations, and finally each task completed Then all 4 threads join the main program and display the final output.This method only works when we have more then one CPU core if we have only one core the Don’t create the thread because we divide the task and perform on only one CPU so it is waste of time to dividing a task and then compute.

Implementation of Multithreading to add 2 ‘2D’ matrices

Same process is being followed for all the operations as depicted in the above picture.

For using multithreading concept we import the ‘Process’ library from ‘multiprocessing’ class. In ‘multithreading’ , processes are spawned by creating a “Process” object and then calling its ‘start()’ method. Process follows the API of “threading.Thread”.

Multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package provides both local and remote parallelism, effectively bypassing the global interpreter lock using subprocesses instead of threads. Thus, multiprocessing modules allow programmers to take full advantage of multiple processors on a particular machine. Works on both Unix and Windows.

Some of the following keywords are used while demonstrating the multithreading in python:

1-start():

Start the thread activity. Must be called at most once per thread object. Ensures that the object’s ‘run()’ method is invoked in a separate thread of control.

2-run():

A method representing thread activity. You can override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with positional and keyword arguments taken from the args and kwargs arguments.

3-join(timeout=None)

Wait until the thread ends. This blocks the calling thread until the thread whose join() method is called terminates — either normally or via an unhandled exception — or until an optional timeout occurs. If the timeout argument is present and not None, it should be a floating-point number specifying the timeout for the operation in seconds (or fractions thereof). Since join() always returns None , you must call is_alive() after join() to decide if a timeout occurred — if the thread is still alive, the join() call has timed out.

4-native_id

Thread ID (TID) of this thread assigned by the OS (kernel). This is a non-negative integer or none if the thread has not been started. See the ‘get_native_id()’ function. This value can be used to uniquely identify that particular thread system-wide (until the thread terminates, after which the value can be recycled by the OS).One Dimensional Array Operations:

Basic Methods

The fundamental operations enabled by an array are listed below.

  • Traverse prints each array element one at a time.
  • Insert a new element at the specified index.
  • Delete the element at the specified index.
  • Searches for an element based on the specified index or value.
  • Update the element at the specified index.

Operation Traverse

Each array element is accessed exactly once for processing during an array traversal operation.

This is also known as a field visit.

Insert Operation:

An insert operation inserts one or more data elements into an array. New elements can be added to the array at the beginning, end, or specified index as needed.
Adding elements to the end of an array is not always necessary.
First-come, first-served field
Insert into an array at a specific index.
Insert into field by index.
Inserts data into the field before the specified index.

Insertion at the Start of a Sequence

When data is inserted at the start, it causes all existing data items to move one step lower. We create and test an algorithm for inserting an element at the start of an array.

Algorithm

Assume that A is an N-element array. MAX specifies the maximum number of items it can hold. First, we find out if there is free space in the field to store an element, and then we start the insertion procedure.

Insertion before an Array’s Given Index

In this case, we are given the position (index) of the field into which we need to insert the new data element (value). The remaining activities are the same as in the previous example, but we search up to index-1, which is one place before the specified index.

Algorithm:

Assume that A is an N-element array. MAX specifies the maximum number of items it can hold.

begin
IF N = MAX, return
ELSE
N = N + 1
SEEK Location index
For All Elements from A[index - 1] to A[N]
Move to next adjacent location
A[index - 1] = New_Element
end

Operation Deletion

Deletion is the process of removing an existing element from an array and reorganizing all its elements.

Algorithm:

Consider the case where LA is a linear array with N entries and K is a positive integer position with value where K<=N. The algorithm for removing an element accessible at the Kth position of LA is as follows.

Start
Set J = K
Repeat steps 4 and 5 while J < N
Set LA[J] = LA[J + 1]
Set J = J+1
Set N = N-1
Stop

Operation of Search

A search for an array element can be done using its value or index.

Algorithm

Consider the case where LA is a linear array with N entries and K is a positive integer position with value where K<=N. The algorithm for finding an element with the value ITEM using a sequential search is as follows.

Start
Set J = 0
Repeat steps 4 and 5 while J < N
IF LA[J] is equal ITEM THEN GOTO STEP 6
Set J = J +1
PRINT J, ITEM
Stop

Operation Update

The update action updates an existing element in the array at a specified index.

Algorithm

Consider the case when LA is a linear array with N items and K is a positive integer’s position with the value where K<=N. The algorithm to update an element accessible at the Kth location of LA is as follows.

Start
Set LA[K-1] = ITEM
Stop

Operation Update

The update action updates an existing element in the array at a specified index.

Algorithm

Consider the case when LA is a linear array with N items and K is a positive integer’s position with the value where K<=N. The algorithm to update an element accessible at the Kth location of LA is as follows.

Start
Set LA[K-1] = ITEM
Stop

Mere har khawab me tu hai basa.Neend churai tune hoke bezubaan.Jo saath me ho har pal ek nasha.Sath na ho har pal ek saza.Sath hasu me jo muskura de tu.Jo tu roye to dhoondu jeene ki wajah.Mere khat me zindagi ke wo lamhe.Likhe jo tune sath haste khelte.Sath rehna tu umr bhar.Ghoomu me warna hoke be sabar.Bewafai tune ki hai.Har lamha jhootha mera.Teri sookhi ankhon me me kuch bhi nahi.Sath chalne ki kasme sath rehne ke wade.Sab mere dil ke sheeshe toot se gayee.Ab mangu me rab se yahi duaa. Na tu dena kisi ko dil ki ye saza.Sath rehna tu har waqt sada.Jona ho to dhoondu jeene ki wajah.

a = [[2, 5], [1, 7]]

b = [[3, 7], [2, 9]]

c = [[0, 0], [0, 0]]

for i in range(0, 2):

for j in range(0, 2):

c[i][j] = 0

for k in range(0, 2):

c[i][j] = c[i][j]+(a[i][k]*b[k][j])

for i in range(0, 2):

for j in range(0, 2):

print(c[i][j])

Have you ever wondered why I just pretend myself so dumb.Only those who know me know what the fuck I’ve gone from.I had a better life with some better words And I planned it out well.You could see a happy face with some really positive words outta that face.That face I don’t where it’s been now.I really want that face right now cuz a thing called life it seems to be a hell and leaves everything in a mess.Everyone just played puns on me including my name, my face and my style.I don’t know why but what the heck is wrong with those guys why don’t you shut your ass up and stand aside!!!.Even when I lost my love I sat aside started thinkin about a lesson that life has taught me and it goes on like.We the own creators of our own problems get eventually stuck in the web of our own solutions we try to make thinkin we could get over it but sad that never happens We struggle hard we die every sec but that mess never gets over us and we still thinkin everything must go on easy but sad that never happens.Some now wear some vision proof glasses.You can never change them. They assume some shitty opinions and block their mind for you and you stand aside let em go and its normal.Sometimes you’re in a situation where your mind over rules your heart just bring up a smile and cool down baby cuz many wars are won with a smile.Listen to me stop thinking about them cuz someone who loves you can’t see you in tears You’ve got 1 life enjoy it at the best and leave the rest don’t spoil out the moment.That’s my words now clap for yourself if you caught me right clap for yourself if at least I could help you change your mind man!!!

Hold your knees tight and move your head like this its time to celebrate yourself you won yourself.Put your hands up and show yourself like this you better changed yourselves like I wanted you.You acted like a stupid got worried for so long.Used to cry for your stupidity you did so long and that doesn’t makes any sense any more.Listen to your open heart and your open mind.And listen hey have a chill time everything comes and everything goes but this passing moment would help you a lot.Hey listen to me stop gritting your teeth might pain you probably kill you and your inner self would always want to teach you hey man you’re not what you can change the spirit and see who I am.You can start to create new wonder just step up your heart and start out to follow me.Hold your knees tight and move your head like this its time to celebrate yourself you won yourself.Put your hands up and show yourself like this you better changed yourselves like I wanted you

Do you even know there’s a name for me.This world calls me the galaxy.Cuz I can do that thing you can barely think.So turn the volume up go listen to me.Get down.I don’t need to laugh.Go get yourself a bit of bath.You’re smelling like you’re jealous.Cool down you bitch.You can’t handle my blow if I come with the flow.You work for the money I work for the fame you got 10% profit me getting a 100% name!!!.You keep everything I don’t need you stay happy filling your pocket full of gold.Why don’t you understand my approach is different our ways is different so just stop following me.You just fill up nuisance upto this level.My mind blows out to hit a chiesel.So just do me a favour get your home just grab out some of your cheapest headphones turn the volume up and play some of my song.Take your pen with you write something that hit you.Make your words a bit of meaningful that rhymes with your life with the people you can relate to.Don’t write something like blah blah blah blah. O come on you’ll be writing a great new song.But hey wait take inspiration meaning never copy my style.Everyone’s got brains to make a unique style.You got no rules to paint a music man.Sit in silence and put your brains for yourselves.

--

--