Skip to content

Instantly share code, notes, and snippets.

@manwar
Last active March 1, 2025 16:39
Show Gist options
  • Select an option

  • Save manwar/20ed64db9a881269deee98c7987aa59a to your computer and use it in GitHub Desktop.

Select an option

Save manwar/20ed64db9a881269deee98c7987aa59a to your computer and use it in GitHub Desktop.
Multi threading in Perl and Python.

-- Back to Index --


In the post, I showed how to do mult-processing in Perl and Python.

Let's try multithreading in Perl:

[Source Code]

#!/usr/bin/env perl use v5.38; use threads; sub worker($t_id) { say "Thread $t_id started."; sleep(2); say "Thread $t_id finished."; return $t_id; } say "Process ID: $$"; say "Starting 5 threads."; my @threads; for my $i (1..5) { my $thread = threads->create(\&worker, $i); push @threads, $thread; } $_->join foreach @threads;

When you execute the above code, you would get something like below:

$ perl multi-threading.pl Process ID: 1996 Starting 5 threads. Thread 1 started. Thread 2 started. Thread 3 started. Thread 4 started. Thread 5 started. Thread 1 finished. Thread 5 finished. Thread 2 finished. Thread 3 finished. Thread 4 finished. 

Similarly in Python, you would do something like below:

[Source Code]

#!/usr/bin/env python3 import os import time import threading def worker(): name = threading.current_thread().name print("Thread " + name + " started.") time.sleep(2) print("Thread " + name + " finished.") print('Process ID: ', os.getpid()) print('Starting 5 threads.') for i in range(5): threading.Thread(target=worker).start()

When you execute the above code, you would get something like below:

$ python3 multi-threading.py Process ID: 1890 Starting 5 threads. Thread Thread-1 (worker) started. Thread Thread-2 (worker) started. Thread Thread-3 (worker) started. Thread Thread-4 (worker) started. Thread Thread-5 (worker) started. Thread Thread-5 (worker) finished. Thread Thread-3 (worker) finished. Thread Thread-2 (worker) finished. Thread Thread-1 (worker) finished. Thread Thread-4 (worker) finished.

-- Back to Index --


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment