r/learnpython • • 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!

2 Upvotes

16 comments sorted by

View all comments

Show parent comment

1

u/Sanduhstorm Sep 14 '26

i need to gain knowledge about computer science on a low level, i don't even know what i/o tasks are lol

2

u/fllthdcrb Sep 14 '26 edited Sep 15 '26

I/O: input/output. It's how computers communicate with the outside world, whether it be reading and writing disks, talking on a network, etc., and it's where programming can get really tricky.

I'm using "task", in that context, in just the common meaning. When talking about async, a task is somewhat analogous to a thread, just without the OS machinery to deal with.

In other words, when you have a task to do that is heavy on I/O, instead of, say, number crunching. Async is well suited to this, as even a single thread can easily handle doing other things while waiting for input. Number crunching benefits from multi-threading on multi-core CPUs, since there is genuinely more to be done simultaneously.