From aa6c62d6011d663b872a159b26758f0b4d37bed5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96mer=20Faruk=20Irmak?= Date: Mon, 29 Mar 2021 15:02:23 +0300 Subject: [PATCH] Fix Issue 21784: Allow detached threads to be joined This is useful when a thread terminates before the caller is able to join(). --- src/core/thread/osthread.d | 5 +++-- test/thread/Makefile | 7 ++++++- test/thread/src/join_detach.d | 20 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 test/thread/src/join_detach.d diff --git a/src/core/thread/osthread.d b/src/core/thread/osthread.d index de2fe56c87e..81a68894d45 100644 --- a/src/core/thread/osthread.d +++ b/src/core/thread/osthread.d @@ -299,7 +299,8 @@ class Thread : ThreadBase } else version (Posix) { - pthread_detach( m_addr ); + if (m_addr != m_addr.init) + pthread_detach( m_addr ); m_addr = m_addr.init; } version (Darwin) @@ -523,7 +524,7 @@ class Thread : ThreadBase } else version (Posix) { - if ( pthread_join( m_addr, null ) != 0 ) + if ( m_addr != m_addr.init && pthread_join( m_addr, null ) != 0 ) throw new ThreadException( "Unable to join thread" ); // NOTE: pthread_join acts as a substitute for pthread_detach, // which is normally called by the dtor. Setting m_addr diff --git a/test/thread/Makefile b/test/thread/Makefile index a5854c29861..3e54c9eca73 100644 --- a/test/thread/Makefile +++ b/test/thread/Makefile @@ -1,6 +1,6 @@ include ../common.mak -TESTS:=fiber_guard_page external_threads tlsgc_sections test_import tlsstack +TESTS:=fiber_guard_page external_threads tlsgc_sections test_import tlsstack join_detach .PHONY: all clean all: $(addprefix $(ROOT)/,$(addsuffix .done,$(TESTS))) @@ -31,6 +31,11 @@ $(ROOT)/tlsstack.done: $(ROOT)/%.done : $(ROOT)/% $(QUIET)$(TIMELIMIT)$(ROOT)/$* @touch $@ +$(ROOT)/join_detach.done: $(ROOT)/%.done : $(ROOT)/% + @echo Testing $* + $(QUIET)$(TIMELIMIT)$(ROOT)/$* + @touch $@ + $(ROOT)/%: $(SRC)/%.d $(QUIET)$(DMD) $(DFLAGS) -of$@ $< diff --git a/test/thread/src/join_detach.d b/test/thread/src/join_detach.d new file mode 100644 index 00000000000..f1515190171 --- /dev/null +++ b/test/thread/src/join_detach.d @@ -0,0 +1,20 @@ +import core.thread; +import core.sync.semaphore; + +__gshared Semaphore sem; + +void thread_main () +{ + sem.notify(); +} + +void main() +{ + auto th = new Thread(&thread_main); + sem = new Semaphore(); + th.start(); + sem.wait(); + while (th.isRunning()) {} + destroy(th); // force detach + th.join(); +}