'Is there an easy way to thread or multiprocess a non-intensive function?

I'm self-learning python so I don't know how to describe this in a way that would be clear, so here's the easiest by proxy example I can come up with in pseudo code:

#where r() is a random number function
objCount = 0
def mainfunc()
  while playgame= True and objCount < 100:
    create(r(time))
    time.sleep(1)
  return None

def create(tmptime)
  global objCount
  objCount = objCount+1
  newobj = plotSomething(r(x),r(y))
  time.sleep(tmptime)
  selfDelete..
  return None

mainfunc() #run it

Instead of it making a random "lived" object every second, it makes a random lived object every second, but waits for it's "life" to expire. I'm trying to just fire this thing off to a sidechain to timeout on its own while still making new things.

All the documentation is getting super involved using asyncio, multithreading, etc.

Is there an easy way to kick this thing out of the main loop and not hold up traffic?



Solution 1:[1]

laziest method for simplicity is :

import concurrent.futures as delayobj
#where r() is a random number function
objCount = 0
def mainfunc()
  global objCount
  with delayobj:
    while objCount < 100:
      delayobj.ThreapoolExecutor().submit(create,tmptime=r(time))
      time.sleep(1)
  return None

def create(tmptime)
  global objCount
  objCount = objCount+1
  newobj = plotSomething(r(x),r(y))
  time.sleep(tmptime)
  selfDelete..
  return None

mainfunc() #run it

thanks again guys

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DreXor akaRobert