Make 2 Functions Run at the Same Time

How to run multiple functions at the same time?

Do this:

from threading import Thread

def func1():
print('Working')

def func2():
print("Working")

if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()

In Python 3, how can I run two functions at the same time?

The target argument has to be a function. You're calling the functions immediately, not passing references to the function.

The functions need to loop.

Use join() to wait for the threads to exit.

Use a lock to prevent reading and writing the file at the same time, which might read the file in a partial state.

import keyboard
from threading import Thread, Lock

mutex = Lock()

def read_file():
while True:
with mutex:
with open("color.txt", "r") as color:
current_color = color.read()
if current_color == "green":
print("GREEN")
elif current_color == "blue":
print("BLUE")
time.sleep(5)

def listen_change():
while True:
if keyboard.is_pressed('g'):
with mutex:
with open("color.txt", "w"):
f.write("green")
elif keyboard.is_pressed('b'):
with mutex:
with open("color.txt", "w"):
f.write("blue")

if __name__ == '__main__':
t1 = Thread(target = read_file)
t2 = Thread(target = listen_change)
t1.start()
t2.start()
t1.join() # Don't exit while threads are running
t2.join()

Make 2 functions run at the same time in loop

This can be done by running the two functions in separate threads.

import time, threading

def func1():
print('1')
time.sleep(2)

def func2():
print('2')

if __name__ == "__main__":
while True:
threading.Thread(target=func1).start()
threading.Thread(target=func2).start()

Executing multiple functions simultaneously

You are doing it correctly. :)

Try running this silly piece of code:

from multiprocessing import Process
import sys

rocket = 0

def func1():
global rocket
print 'start func1'
while rocket < sys.maxint:
rocket += 1
print 'end func1'

def func2():
global rocket
print 'start func2'
while rocket < sys.maxint:
rocket += 1
print 'end func2'

if __name__=='__main__':
p1 = Process(target = func1)
p1.start()
p2 = Process(target = func2)
p2.start()

You will see it print 'start func1' and then 'start func2' and then after a (very) long time you will finally see the functions end. But they will indeed execute simultaneously.

Because processes take a while to start up, you may even see 'start func2' before 'start func1'.

How to have two functions running simultaneously with python?

One of your options is to use the asyncio module.

First of all, import the asyncio module with import asyncio. Replace your def functions to async def functions.

Second of all, replace time.sleep() with await asyncio.sleep(). You no longer need the time module because of this step.

Thirdly, create a new function, normally called main(). You can take the following code snippet for reference:

async def main():
task1 = asyncio.create_task(
short_task())
task2 = asyncio.create_task(
long_task())
await task1
await task2

Finally, run the whole main() code with asyncio.run(main()). Your final code should look like this:

import asyncio
async def short_task():
await asyncio.sleep(2)

async def long_task():
await asyncio.sleep(4)

async def main():
task1 = asyncio.create_task(
short_task())
task2 = asyncio.create_task(
long_task())
await task1
await task2

You may use a simple code snippet to proof that the whole process took 4 seconds.

Is there a way to run two functions at the same time(simultaneously/asynchrounously) with one function as an infinite loop?

Google apps script executes synchronously. For the most part, simultaneous/paralell processing is not possible. Based on your script, it seems you want two functions to run simultaneously onOpen. Possible workarounds(Some not tested):

Workaround#1: Use Different projects

  • Create a new project: In the editor(Legacy/Old editor only)>File>New>Project
  • First project's onOpen() will run infLoop()
  • Second project's onOpen() will run runScript()
  • Both functions will run simultaneously on open.

Workaround#2: Simple and Installable trigger1

  • Create a installable trigger for runScript()
  • Simple trigger onOpen() will run infLoop()
  • Both functions will run simultaneously on open.
  • You could use two installable triggers instead of simple and installable trigger.

Workaround#3: Web apps: Call from client

  • If there is a sidebar open or if a sheet is opened from web app, it is possible to call server functions repeatedly through google.script.run(which run asynchrously)

  • Here It is possible to run a function for 6 minutes(current runtime). But by repeatedly calling the server function, you can run the function for a long time(upto 90minutes/day = current trigger runtime quota/day)

Workaround#4: Web apps: UrlFetchApp#fetchAll2

  • UrlFetchApp#fetchAll runs asynchronously
  • Once a web app is published, the published url can be used with query parameters. If a function name is sent as a parameter and doGet() executes the function, .fetchAll can be used to multiple functions asynchronously.

Workaround#5: onEdit/onChange

  • If a edit is made, both functions(onEdit/onChange) run simultaneously.

Workaround#6: Sheets API/onChange

  • If a add-on/script makes a change through sheets api, onChange may get triggered. If triggered, every change made through sheets api causes onChange to run asynchronously.


Related Topics



Leave a reply



Submit