Andriy
Andriy

Reputation: 1610

How to lock running some block of code within specific thread in Gevent?

Simplified code looks like

import gevent
from requests import get
from gevent.monkey import patch_all; patch_all()


def f1():
    print("Thread 1 start")
    x = get('https://www.google.com')
    print("Thread 1 end")


def f2():
    print("Thread 2")


gevent.joinall([
    gevent.spawn(f1),
    gevent.spawn(f2)
])

And the output is expected:

Thread 1 start
Thread 2
Thread 1 end

I need to lock calling of the get request. So, I need to get the following output:

Thread 1 start
Thread 1 end
Thread 2

How achieve such get request locking?

Upvotes: 2

Views: 364

Answers (1)

kyrione
kyrione

Reputation: 21

you should do like this:

import gevent
from requests import get
from gevent.monkey import patch_all; patch_all()

from gevent.lock import Semaphore

sem = Semaphore()

def f1():
    sem.acquire()
    print("Thread 1 start")
    gevent.sleep(0.1)
    print("Thread 1 end")
    sem.release()

def f2():
    with sem:
        print("Thread 2")

gevent.joinall([
    gevent.spawn(f1),
    gevent.spawn(f2)
])

Upvotes: 1

Related Questions