Skip to content

Potential segmentation fault when subtyping greenlet #245

Closed
@fygao-wish

Description

@fygao-wish

Hi,

I recently ran into some weird errors when running an application with subtyped greenlet.
Some example error messages:

  • Fatal Python error: GC object already tracked
  • AttributeError: run
  • Segmentation fault

After some digging, I found the root cause is that when a greenlet is resurrected, it keeps the object alive, but the subtype is decrefed. Similar issue here: https://bugs.python.org/issue8212

Here's a snippet to repro the problem:

from greenlet import getcurrent, greenlet
from concurrent.futures import ThreadPoolExecutor
import sys
import time

class MyGreenlet(greenlet):
    def __init__(self, *args, **kwargs):
        super(MyGreenlet, self).__init__(*args, **kwargs)

    def switch(self):
        super(MyGreenlet, self).switch()

TPOOL = ThreadPoolExecutor(max_workers=1)
# In main thread, we start greenlets and save them in the glets array
# In order to trigger greenlet resurrect easily, we start another thread to clear the glets array
glets = []

def clean_greenlets():
    while True:
        time.sleep(1)
        if glets:
            glets.clear()

# start a thread to clear the glets list
TPOOL.submit(clean_greenlets)

def gr_run():
    while True:
        time.sleep(0.10)
        print("{}".format(sys.getrefcount(MyGreenlet)))
        getcurrent().parent.switch()

while True:
    glet = MyGreenlet(gr_run)
    glets.append(glet)
    glet.switch()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions