• Assume that you have an array (data=[]) containing 500,000 elements and that each element has been assigned a random value between 1 and 10 (random.randint(1,10)) .
for i in range (500000):data[i]=random.randint()
• Allow the users to determine the number of worker threads (N). The user can enter a value between 1 and 10. Invalid values should result in a warning message and the thread count being set to 5. • Work out a method of automatically partitioning the array into N equal segments, where N is the number of worker threads (threadCount). You cannot create subarrays to handle this problem; you must work out a method of partitioning the original array based on indices. A hint is provided below assuming that the user has entered a threadCount of 4.
Segment 1 (125,000 elements) Segment 2 (125,000 elements) Segment 3 (125,000 elements) Segment 4 (125,000 elements)
• Determine a method to spawn your threads so that each thread is assigned a segment of the array to operate on. These threads should create a sum of the elements for their allotted segment. The single threaded function prototype is given below:
def summation(st, end, threadIndex):
where: st and end represent the start and end points of the array segment, and index is the thread number.
Your must determine the locking mechanism to ensure the program can run concurrently on the array.
• After each thread has completed its work the main program should compute the final average by summing the sub-sums and diving by the total number of array elements.
Final Exercise: Can you extend your program so that the array is populated with random numbers using your worker threads? My Code:
import random
import thread
def su(st,end,i):global subtotal, data, locksfor index in range(st,end+i):subtotal[i] += data[index]lock.release()numth = int(100)data = list(range(numth))for index in range(len(data)):data[index] = random.randint(1,10)wt=int(input("enter the number of working threads:"))locks = list(range(wt))subtotal = list(range(wt))seg = len(data)/wtst=0for i in range(wt):st= i * segend = st *seg -1thread.start_new_thread(su, ())locks = lock.acquire()
avg = sum(subtotal)/len(data)print(avg)