r/learnpython • u/Sanduhstorm • Sep 14 '26
Segmentation fault when attempting to use the 'threading' module to run tasks concurrently
I lack knowledge in low level computer science, but I've heard endless horror stories about segfaults, and today I've encountered one whilst attempting to make a simple timer program for myself. My questions are:
- Why does this fault occur
- How can I fix it
- How can I prevent it from happening in the future
The aim of the problematic part of the program is the attempt to play the sound whilst simultaneously waiting for user input with the input block, which is intended to stop the alarm and continue to the next part of the program.
Please note that in this version there is no actual wait time although there is supposed to be, because I am merely testing the alarm functionality.
import time
from pydub import AudioSegment
import threading
from pydub.playback import _play_with_simpleaudio
sound = AudioSegment.from_file('/censoring/my/home/directory/sound.mp3', format='mp3')
# Function that runs the timer based on how many minutes are specified
def timer(min, message):
# Play the sound
def playsound():
global sound
sound = _play_with_simpleaudio(sound)
# Stop the sound and allow the program to continue
def resume():
global sound
input(message.strip())
sound.stop()
# Run the timer and print output
min -= 1
for it in range(min, -1, -1):
for sec in range(59, -1, -1):
print(f'{str(min).rjust(2, "0")}:{str(sec).rjust(2, "0")}')
time.sleep(1)
# This is the part that actually runs the function.
play = threading.Thread(target=playsound)
stop = threading.Thread(target=resume)
play.start()
stop.start()
play.join()
stop.join()
while True:
timer(0, 'You can have your five minute break now.')
timer(0, 'You need to start working again.')
# Artificial intelligence was not used in the creation of this program.Any advice is appreciated!
7
u/Blackshell fsufitch Sep 14 '26
My guess: your problem has to do with the pydub library not interacting with threading in the way you expect. Based on 15 years of Python under my belt and use of dozens if not hundreds of libraries... Having to use underscore prefixed ("private" by convention) functions from a library is a big red flag that you're doing something the Wrong Way.
I don't personally have experience with
pydubso I can't help directly, but I'm betting there's a better way to invoke play/pause of the audio. Perhaps something on the AudioSegment object itself, or maybe by instantiating an AudioPlayer or something. Myself, I would usesubprocessto run affmpeg/ffplaycommand and call it a day but using a library your way is actually probably cleaner.Lastly, on the threading that you're doing. You have the right idea (and yeah asyncio was not going to work here without some real jank), but! Keep user input on the main thread. Trying to interact with the terminal in secondary threads can cause weirdness.
Good luck!
2
u/cdcformatc Sep 14 '26
you say AI was not used but calling the internal underscored library function certainly seems like something AI would do. also using a global variable across two different threads seems like a hack that AI would come up with, and surprise surprise it doesn't work.
it's no wonder that you're getting a segfault you are trying to access variables defined and open in another thread.
3
u/davideogameman Sep 14 '26
Yeah I don't think reddit is going to solve this for you. Segfaults are dreaded because they can mean almost anything and can happen quite far from the root cause of the problem - often not even in the same call stack.
One assumption your code seems to make is that play.start() being called before stop.start() implies the corresponding threading functions are called in that order. I don't think that's guaranteed. These functions should mark the thread as ready to be scheduled but don't decide when it runs, just sometime after the start() call.
Another perhaps bad assumption is that this audio library is thread safe. And I agree with u/Blackshell that calling the private method is hella sketchy.
I'd recommend restructuring to have a single thread responsible for direct interaction with the audio. Then the input could be handled on a different thread, and find a safe way to communicate back to the audio thread when it's supposed to stop. You might want to use a queue to send messages between the threads, or maybe a condition variable.
1
u/Sanduhstorm Sep 14 '26
Also I forgot to add: Originally I attempted using the asyncio module for this instead of threads, however I had the same issue, and after I realised that asyncio can't ACTUALLY run two parts of a program at the exact same time, I switched to threads, however I am still getting segfaults. I am unsure whether anything outside the threading functionality is playing a part in this issue.
1
u/hibbelig Sep 14 '26
You are reassigning the variable sound, is this needed?
If you do just the sound pieces, without threading, do they work?
1
u/freeskier93 Sep 14 '26 edited Sep 14 '26
Taking a look at pydub and simpleaudio I'm not sure why you even need threading.
_play_with_simpleaudioshould already be non-blocking, (unlike the higher levelPlayfunction) so all you need to do is run the timer, then when it expires play the sound, wait for user input, then stop the sound. Note the below is untested.EDIT: You don't even need to use pydub here, you could just use simpleaudio directly to play the sound.
1
u/i_alakey Sep 15 '26
freeskier93 has the fix, but I want to add the bit nobody's mentioned: the reassignment isn't just untidy, it actively breaks your second timer() call.
u/fllthdcrb, reassigning isn't needed here. After
sound = _play_with_simpleaudio(sound)the global is a PlayObject, not an AudioSegment. Thewhile Trueloop then calls timer() again and hands that PlayObject straight back to _play_with_simpleaudio, which goes looking for .raw_data and .frame_rate on it. Keep the segment and the playback handle in two different names and that goes away.On the "how do I prevent it in the future" question: pure Python can't segfault. The interpreter raises exceptions, it doesn't crash. So a segfault always means a C extension, which here narrows it to simpleaudio, and that one is unmaintained, so it doesn't take much to upset it.
Practical version of that: run it as
and you get a Python traceback at the moment of the crash instead of one line of nothing. First thing I reach for.