# How to kill a thread

**URL:** <https://users.rust-lang.org/t/how-to-kill-a-thread/96422>\
**Category:** uncategorized\
**Created:** [July 4, 2023, 1:10pm UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422 "2023-07-04T13:10:33Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![juli1](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/juli1/32/34900_2.png) [@juli1](https://users.rust-lang.org/u/juli1)\
**Post date:** [July 4, 2023, 1:10pm UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422/1 "2023-07-04T13:10:33Z")

</div>

I have a program where I execute third-party JavaScript code using [deno](https://github.com/denoland/deno). The objective is to execute the JavaScript code for 1 second max and if the code takes too long to execute, stop executing it and return.

I have been searching how to do that.

I am using the following code to do so

- Create a Mutex that will contain the JS result with a condition variable
- Create a thread that execute the JS code
- Wait on the condition variable until the 1000 ms delay expires
- If the JS code is executed, post on the condition variable to release the thread
- drop the create thread for the JS execution

The objective is to make sure the JS code that execute the infinite loop is killed. And that is done with `drop`.

Is the solution sound? Or should I proceed differently?

```rust
    let pair = Arc::new((Mutex::new(None), Condvar::new()));
    let pair2 = Arc::clone(&pair);

    let thr = thread::spawn(move || {
        let (lock, cvar) = &*pair2;

        yield_now();
        let res = execute_javascript_code(code);
        let mut started = lock.lock().unwrap();
        *started = Some(res);
        cvar.notify_one();
    });

    let (lock, cvar) = &*pair;
    let started = lock.lock().unwrap();

    let cond_result = cvar.wait_timeout(started, Duration::from_millis(1000));

    drop(thr);
    match cond_result {
        Ok(v) => {
            if v.1.timed_out() {
            }
        }
  }

```

---

<div class="post-metadata">

**Author:** ![Hyeonu](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/hyeonu/32/7970_2.png) [@Hyeonu](https://users.rust-lang.org/u/Hyeonu)\
**Post date:** [July 4, 2023, 1:29pm UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422/2 "2023-07-04T13:29:47Z")

</div>

No. Dropping `JoinHandle` returned by `thread::spawn()` makes the thread keep running in background. There's no reliable way to kill running thread externally. But you can kill external processes. Why don't you invoke deno as a separate process and kill it on timeout?

---

<div class="post-metadata">

**Author:** ![jonh](https://avatars.discourse-cdn.com/v4/letter/j/dec6dc/32.png) [@jonh](https://users.rust-lang.org/u/jonh)\
**Post date:** [July 4, 2023, 2:16pm UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422/3 "2023-07-04T14:16:02Z")

</div>

If your not going down the external process route then you have to dig into how deno works.  
[terminate\_execution](https://docs.rs/v8/0.74.1/v8/struct.IsolateHandle.html#method.terminate_execution) might be what you want. Either would need someone with knowledge of how to get there and/or spend time reading the code.

---

<div class="post-metadata">

**Author:** ![juli1](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/juli1/32/34900_2.png) [@juli1](https://users.rust-lang.org/u/juli1)\
**Post date:** [July 4, 2023, 3:06pm UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422/4 "2023-07-04T15:06:52Z")

</div>

The problem with the external process route is the associated cost. I am running thousands time this routine and do not want to start thousands of processes. I will investigate the `terminate_execution` route.

---

<div class="post-metadata">

**Author:** ![juli1](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/juli1/32/34900_2.png) [@juli1](https://users.rust-lang.org/u/juli1)\
**Post date:** [July 4, 2023, 5:20pm UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422/5 "2023-07-04T17:20:53Z")

</div>

The problem with the `terminate_execution` is that I need to share a mutable `JsRuntime` between threads. The `JsRuntime` also uses raw pointers and when I try to have a program and I use the `runtime` in the thread, I get

```rust
*const c_void` cannot be sent between threads safely

```

Crates like [fragile](https://github.com/mitsuhiko/fragile) only share non-mutable reference.

Any idea about how to share mutable reference of a value that has raw pointers between thread?

---

<div class="post-metadata">

**Author:** ![simonbuchan](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/simonbuchan/32/19939_2.png) [@simonbuchan](https://users.rust-lang.org/u/simonbuchan)\
**Post date:** [July 5, 2023, 9:48am UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422/6 "2023-07-05T09:48:46Z")

</div>

I'm a bit confused, where's `JsRuntime` coming from? The link goes to `IsolateHandle`, which is the thing you would hand out to kill the execution, and that's from an `Isolate`, which should live forever on one thread. So if you want to hand out the handle to terminate execution you need to do something like:

```rust
let (tx, rx) = channel();
spawn(|| {
  let isolate = Isolate::new(...);
  tx.send(isolate.thread_safe_handle());
  ...
});
let handle = rx.recv();
...
handle.terminate_execution();

```

`channel` here is probably the thing you're missing: [channel in std::sync::mpsc - Rust](https://doc.rust-lang.org/stable/std/sync/mpsc/fn.channel.html)

---

<div class="post-metadata">

**Author:** ![juli1](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/juli1/32/34900_2.png) [@juli1](https://users.rust-lang.org/u/juli1)\
**Post date:** [July 5, 2023, 1:45pm UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422/7 "2023-07-05T13:45:01Z")

</div>

Thank you for your answer and thank you so much for your suggestion! You are correct about the `JsRuntime`. It was declared in the `execute_javascript_code` function and I need to bring it back outside of the function.

I will try what you say and report if it works here!

---

<div class="post-metadata">

**Author:** ![juli1](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/juli1/32/34900_2.png) [@juli1](https://users.rust-lang.org/u/juli1)\
**Post date:** [July 5, 2023, 9:34pm UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422/8 "2023-07-05T21:34:45Z")

</div>

Thank you so much for your help, it worked!

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [October 3, 2023, 9:35pm UTC](https://users.rust-lang.org/t/how-to-kill-a-thread/96422/9 "2023-10-03T21:35:26Z")

</div>

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.
