Search code examples
pythonsegmentation-faultpython-multithreadingpyglet

Python loading animation in a thread giving segmentation fault


Here's the code I have created to load animations in background using pyglet.resource.animation() function, while the app does some other things.

import pyglet
import threading

animations = dict()

class LoadingThread(object):
    def __init__(self):
        thread = threading.Thread(target=self.run, args=())
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        loadAnimations()
        print("Loaded all animations.")


def loadAnimations():
    global animations
    print("In loadAnimations")
    for animation in os.listdir(os.getcwd()):
        if animation.endswith(".gif"):
            print(animation)
            #Gives segmentation fault here
            animations[animation] = pyglet.resource.animation(animation)
    print("Loaded animations")

thread = LoadingThread()

Runs well when called normally without a thread. If there is any other way to deal with loading animations in background in pyglet, please suggest.

Thanks.


Solution

  • As suggested by @Frank Merrow. The problem here was that I was using the function pyglet.resource.animation("filename.gif") function in my main thread too. So it was creating a segmentation fault. I found another function that can also load animation.

    pyglet.image.load_animation("filename.gif")

    Using this solved my problem.

    Also this problem can be solved by starting two threads synchronously running main flow and the background work.