Shortest Code that creates a Deadlock

Dyalog APL (10)

⎕TSYNC⎕TID

⎕TSYNC makes the thread wait until the given thread ends, ⎕TID gives the current thread.

Dyalog APL can recognize deadlocks though, so it immediately responds with

DEADLOCK

The fun thing is, you don't even need to spawn any extra threads, making the UI thread wait for itself is plenty.

If this is cheating and new threads are actually required, you can do it in 27 characters:

{∇⎕TSYNC&{⎕TSYNC⎕TID+1}&0}0

F & x runs F in a new thread on value x, and returns the thread ID. So:

  • {⎕TSYNC⎕TID+1}&0 creates a thread that will synchronize with the thread whose ID is one higher than its own,
  • ⎕TSYNC& creates a new thread that will synchronize with the previous thread, and which gets an ID one higher than the thread that was just created (assuming nothing else is creating threads).
  • causes an infinite loop (so we keep creating threads until there's a deadlock).

This will deadlock as soon as the second thread gets created before the first one starts running, which is pretty soon:

9:DEADLOCK

Go, 42

package main
func main(){<-make(chan int)}

Apologies, downvoter, for not providing how it works. This creates an anonymous channel of ints and reads from it. This pauses the main thread until a value gets sent down the channel, which obviously never happens since no other threads are active, and thus, deadlock.


Ruby, 39 characters

T=Thread;t=T.current;T.new{t.join}.join

The idea to use a cross-join shamelessly stolen from Johannes Kuhn's Java answer.

We can shave off four characters (getting to 35) if we tune the code to a specific environment. JRuby's console IRB is single-threaded:

T=Thread;T.new{T.list[0].join}.join


This is my previous solution:

getting a thread stuck on a mutex is easy:

m=Mutex.new;2.times{Thread.new{m.lock}}

but this isn't a proper deadlock, because the second thread is technically not waiting for the first thread. "hold and wait" is a neccessary condition for a deadlock according to Wikipedia. The first thread doesn't wait, and the second thread doesn't hold anything.

Ruby, 97 95 characters

m,n=Mutex.new,Mutex.new
2.times{o,p=(m,n=n,m)
Thread.new{loop{o.synchronize{p.synchronize{}}}}}

this is a classic deadlock. Two threads compete for two resources, retrying if they succeed. Normally they get stuck within a second on my machine.

But, if having infinitely many threads (none of which consumes CPU infinitely and some of which deadlock) is OK,

Ruby, 87 85 characters

m,n=Mutex.new,Mutex.new
loop{o,p=(m,n=n,m)
Thread.new{o.synchronize{p.synchronize{}}}}

According to my test, it fails after the thread count reaches about 4700. Hopefully it doesn't fail until each thread had a chance to run (thus either deadlocking or finishing and freeing space for a new one). According to my test, the thread count doesn't drop after the failure occurs, meaning that a deadlock did occur during the test. Also, IRB died after the test.