Skip to content

Instantly share code, notes, and snippets.

@SureshKL
Last active January 23, 2019 11:57
Show Gist options
  • Save SureshKL/754a4c7be2e4a256ca04393c914905bb to your computer and use it in GitHub Desktop.
Save SureshKL/754a4c7be2e4a256ca04393c914905bb to your computer and use it in GitHub Desktop.
Python: gevent - synchronous/asynchronous execution
import logging
import time
import gevent
logging.basicConfig(
format='%(asctime)s - %(levelname)10s - [%(threadName)s-%(thread)d] - [%(processName)s-%(process)s]- %(message)s',
level=logging.DEBUG)
logger = logging.getLogger(__name__)
def synchronous_task(taskid):
logger.info(f'Synchronous task {taskid} started ')
time.sleep(0.2)
logger.info(f'Synchronous task {taskid} completed')
def asynchronous_task(taskid):
logger.info(f'Synchronous task {taskid} started')
gevent.sleep(3)
logger.info(f'Synchronous task {taskid} completed')
def synchronous():
[synchronous_task(i) for i in range(5)]
def asynchronous():
threads = [gevent.spawn(asynchronous_task, i) for i in range(5)]
gevent.joinall(threads)
logger.debug('*** Synchronous ***')
synchronous()
logger.debug('*** Asynchronous ***')
asynchronous()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment