0

Actually New Here And I will Try my best to Describe My Issue. I am Having a a for loop and i wanted that for loop executed by help of threading . Like :

for i in range(0,100):
    print(i)

and i want 4-5 threads to execute it and print the value of i(remember not to run 4-5 times same loop). ok i will describe same as another way :

i am having 10 textbox in a webpage and i want to fill all the boxes to be filled by selenium. How can i do that ?I use for loop like:

for texbox in texoxelements:
    textbox.send_keys(texoxelements.index)

AND HERE I WANT TO FILL THAT ALL TEXTBOXES IN A LOOP AND USING THREADING BECAUSE THE ALL TEXTBOXES SHOULD FILLED IN A SECOEND.

Here another example:

def myfunc(number):
    for i in range(0,number):
        print(i)#or do some other stuffs
    
    
#here i want something to execute that function once and solve that forloop in a threading method for which
#it will  take less that a secoend to do stuffs and complete the for loop.


#_____Like_______

myfunc(25)
#and it should print 25 in in that for loop ad using of threading.
#secuence print is not mandatory

I hope i was able to describe my issue in two example.Can anyone please help me with that ? I am new here .Small kindness is appriciated.

jay kishan
  • 82
  • 1
  • 7
  • Looks like you want to launch parallel i/o-bound tasks. I would recommend you to use the built-in `concurrent.futures` library. See an example here: https://docs.python.org/3.8/library/concurrent.futures.html#threadpoolexecutor-example – thomask Nov 23 '21 at 10:18
  • A `for` loop is a well defined thing; that includes that it works sequentially. If you want *something like* a `for` loop but threaded, the answers here and on the duplicate should cover that. If you want to *redefine* what a `for` loop means, you are looking for meta-programming such as bytecode modification or import hooks. Do you really want the latter? – MisterMiyagi Nov 23 '21 at 10:55
  • @MisterMiyagiNot that much pro bro... Just tell me one thing should i use for loop in a thread or leave it as it is ? – jay kishan Nov 23 '21 at 11:54

1 Answers1

0

Use a Pool.

from multiprocessing.pool import ThreadPool

def worker(index, texbox):
    texbox.send_keys(index)
    
    
workers = 4
pool = ThreadPool(workers)
pool.starmap(worker, enumerate(texoxelements))
Some Guy
  • 576
  • 1
  • 4
  • 17
  • Sorry I updated the question little bit more easy .Can you read again ?I meant to run one for loop inside a function. – jay kishan Nov 23 '21 at 10:33