Skip to content
This repository has been archived by the owner on Oct 12, 2022. It is now read-only.

Commit

Permalink
Fix Issue 21784: Allow detached threads to be joined
Browse files Browse the repository at this point in the history
This is useful when a thread terminates before the
caller is able to join().
  • Loading branch information
omerfirmak committed Mar 30, 2021
1 parent 30f7007 commit aa6c62d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/core/thread/osthread.d
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion 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)))
Expand Down Expand Up @@ -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$@ $<

Expand Down
20 changes: 20 additions & 0 deletions 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();
}

0 comments on commit aa6c62d

Please sign in to comment.