How do I force an end to a thread that is blocking?

This thread is blocked by a named pipe, is there a way to close it in another thread? Thanks.

std::thread::spawn(move || {
	let last_name = title.as_str().encode_utf16().chain(Some(0)).collect();

	let pipe = CreateNamedPipeW(last_name.as_ptr(), 3, 0, 255, 0, 0, 0, null_mut());

	ConnectNamedPipe(pipe, null_mut());		// blocked

	(std::mem::transmute::<_, extern "C" fn(u32)>(ptr))(pipe as _);

In general, it is not sound to kill a thread, because that thread might be holding locks or other state which would become "stuck" at the moment it's terminated without unwinding. Your options are:

  • Use a non-blocking IO mechanism.
  • Run the thing you need to be able to stop as a subprocess. The address space separation ensures that the entire subprocess going away can't harm your main process.

Thank you. I searched for some pipeline asynchronous methods. It successfully unblocks. :grinning:

The complications of (synchronous) threads was a motivation for me to look at async Rust. Of course async also has some other advantages (as well as some disadvantages).

For a task in Tokio, for example, there is an abort method on the JoinHandle.

This might seem naive, but what about closing the other end of the pipe? That should result in a read error which will unblock the blocked thread so you can kill it.

Closing the other pipe of the end sounds like a good idea. Note, however, that when writing to a pipe that has been closed on the other end, certain measures must be taken as by default some operating systems will kill the whole process (e.g. with SIGPIPE on Linux or BSD). That behavior can be changed (e.g. by ignoring the signal).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.