Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/core/core.pri
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ HEADERS += $$PWD/processquit.h
SOURCES += $$PWD/processquit.cpp

HEADERS += \
$$PWD/rustthread.h \
$$PWD/test.h \
$$PWD/tnetstring.h \
$$PWD/httpheaders.h \
Expand All @@ -31,6 +32,7 @@ HEADERS += \
$$PWD/layertracker.h

SOURCES += \
$$PWD/rustthread.cpp \
$$PWD/test.cpp \
$$PWD/tnetstring.cpp \
$$PWD/httpheaders.cpp \
Expand Down
4 changes: 2 additions & 2 deletions src/core/defercalltest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@

#include "defercall.h"
#include "eventloop.h"
#include "rustthread.h"
#include "test.h"
#include <thread>

// loop_advance should process enough events to cause the calls to run, without sleeping, in order
// to prove the calls are run immediately
Expand All @@ -44,7 +44,7 @@ static std::tuple<int, int> runDeferCall(std::function<void()> loop_advance) {

// Spawns a thread, triggers the deferCall from it, then waits for thread to finish
static void callNonLocal(DeferCall *deferCall, std::function<void()> handler) {
std::thread thread([=] { deferCall->defer(handler); });
RustThread::JoinHandle thread = RustThread::spawn([=] { deferCall->defer(handler); });
thread.join();
}

Expand Down
1 change: 1 addition & 0 deletions src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub mod select;
pub mod shuffle;
pub mod task;
pub mod test;
pub mod thread;
pub mod time;
pub mod timer;
pub mod tnetstring;
Expand Down
54 changes: 54 additions & 0 deletions src/core/rustthread.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright (C) 2026 Fastly, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "rustthread.h"

#include <assert.h>

static void call_and_delete_function(void *ctx) {
std::function<void()> *f = reinterpret_cast<std::function<void()> *>(ctx);
(*f)();
delete f;
}

namespace RustThread {

JoinHandle::JoinHandle() : handle_(nullptr, ffi::thread_forget) {}

JoinHandle::JoinHandle(ffi::ThreadJoinHandle *handle) : handle_(handle, ffi::thread_forget) {}

void JoinHandle::join() {
if (handle_) {
ffi::thread_join(handle_.release());
}
}

JoinHandle spawn(std::function<void()> f, const std::string &name) {
// Move the function to the heap. The spawned thread will take care of destruction.
std::function<void()> *f_heap = new std::function<void()>(f);

const char *name_c = nullptr;
if (!name.empty())
name_c = name.c_str();

ffi::ThreadJoinHandle *handle =
ffi::thread_spawn(call_and_delete_function, reinterpret_cast<void *>(f_heap), name_c);
assert(handle);

return JoinHandle(handle);
}

} // namespace RustThread
45 changes: 45 additions & 0 deletions src/core/rustthread.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2026 Fastly, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef RUST_THREAD_H
#define RUST_THREAD_H

#include "rust/bindings.h"
#include <functional>
#include <memory>
#include <string>

namespace RustThread {

class JoinHandle {
public:
JoinHandle();

void join();

private:
std::unique_ptr<ffi::ThreadJoinHandle, void (*)(ffi::ThreadJoinHandle *)> handle_;

JoinHandle(ffi::ThreadJoinHandle *handle);

friend JoinHandle spawn(std::function<void()> f, const std::string &name);
};

JoinHandle spawn(std::function<void()> f, const std::string &name = "");

} // namespace RustThread

#endif
112 changes: 112 additions & 0 deletions src/core/thread.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Copyright (C) 2026 Fastly, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

use std::thread;

mod ffi {
use super::*;
use std::ffi::{c_char, CStr};
use std::ptr;

mod sendable_pointer {
pub struct SendablePointer<T>(*mut T);

impl<T> SendablePointer<T> {
// SAFETY: `p` must be safe to move to another thread.
pub unsafe fn new(p: *mut T) -> Self {
Self(p)
}

pub fn get(&self) -> *mut T {
self.0
}
}

unsafe impl<T> Send for SendablePointer<T> {}
}

use sendable_pointer::SendablePointer;

pub struct ThreadJoinHandle(thread::JoinHandle<()>);

/// `name` can be used to supply an optional name for the thread. If it is null, no explicit
/// name will be set on the thread.
//
/// SAFETY: `ctx` must be safe to use from another thread, and `f` must be safe to call from
/// another thread with `ctx` as its argument. If `name` is non-null, it must point to a valid
/// C string.
#[no_mangle]
pub unsafe extern "C" fn thread_spawn(
f: unsafe extern "C" fn(*mut libc::c_void),
ctx: *mut libc::c_void,
name: *const c_char,
) -> *mut ThreadJoinHandle {
let name = if !name.is_null() {
// SAFETY: We assume `name` is valid.
unsafe {
match CStr::from_ptr(name).to_str() {
Ok(s) => Some(s),
Err(_) => return ptr::null_mut(), // Invalid UTF-8
}
}
} else {
None
};

// SAFETY: `ctx` is safe to move to another thread.
let ctx = unsafe { SendablePointer::new(ctx) };

let builder = thread::Builder::new();

let builder = if let Some(name) = name {
builder.name(name.to_string())
} else {
builder
};

let thread = builder.spawn(move || unsafe { f(ctx.get()) }).unwrap();

Box::into_raw(Box::new(ThreadJoinHandle(thread)))
}

/// Blocks until the thread completes and consumes the handle, invaliding the pointer.
///
/// SAFETY: `handle` must point to a valid handle returned by `thread_spawn` that has not yet
/// been invalidated.
#[no_mangle]
pub unsafe extern "C" fn thread_join(handle: *mut ThreadJoinHandle) {
assert!(!handle.is_null());

// SAFETY: We assume `handle` is valid.
let thread = unsafe { Box::from_raw(handle).0 };

thread.join().unwrap();
}

/// Discards the handle and leaves the thread running, invaliding the pointer.
///
/// SAFETY: `handle` must point to a valid handle returned by `thread_spawn` that has not yet
/// been invalidated.
#[no_mangle]
pub unsafe extern "C" fn thread_forget(handle: *mut ThreadJoinHandle) {
assert!(!handle.is_null());

// SAFETY: We assume `handle` is valid.
let thread = unsafe { Box::from_raw(handle).0 };

drop(thread);
}
}
15 changes: 3 additions & 12 deletions src/proxy/domainmap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
#include "filewatcher.h"
#include "log.h"
#include "routesfile.h"
#include "rustthread.h"
#include "timer.h"
#include <QCoreApplication>
#include <QDir>
Expand All @@ -38,8 +39,6 @@
#include <QTextStream>
#include <QWaitCondition>
#include <assert.h>
#include <pthread.h>
#include <thread>

#define WORKER_THREAD_TIMERS 10
#define WORKER_THREAD_SOCKETNOTIFIERS 1
Expand Down Expand Up @@ -708,7 +707,7 @@ class DomainMap::Worker {
class DomainMap::Thread {
public:
QString fileName;
std::thread thread;
RustThread::JoinHandle thread;
std::unique_ptr<EventLoop> loop;
std::unique_ptr<Worker> worker;
QMutex m;
Expand All @@ -730,15 +729,7 @@ class DomainMap::Thread {
void start() {
QMutexLocker locker(&m);

thread = std::thread([=] {
#ifdef Q_OS_MAC
pthread_setname_np("domainmap");
#else
pthread_setname_np(pthread_self(), "domainmap");
#endif

run();
});
thread = RustThread::spawn([=] { run(); }, "domainmap");

w.wait(&m);
}
Expand Down
15 changes: 3 additions & 12 deletions src/proxy/proxyapp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#include "proxyargsdata.h"
#include "proxyengine.h"
#include "rust/bindings.h"
#include "rustthread.h"
#include "settings.h"
#include "simplehttpserver.h"
#include "timer.h"
Expand All @@ -42,9 +43,7 @@
#include <QWaitCondition>
#include <assert.h>
#include <boost/algorithm/string.hpp>
#include <pthread.h>
#include <string>
#include <thread>
#include <unistd.h>
#include <vector>

Expand Down Expand Up @@ -136,7 +135,7 @@ class EngineWorker {
/// Wraps an Engine instance to run in its own thread
class EngineThread {
public:
std::thread thread;
RustThread::JoinHandle thread;
QMutex m;
QWaitCondition w;
Engine::Configuration config;
Expand All @@ -156,15 +155,7 @@ class EngineThread {

QMutexLocker locker(&m);

thread = std::thread([=] {
#ifdef Q_OS_MAC
pthread_setname_np(name.toUtf8().data());
#else
pthread_setname_np(pthread_self(), name.toUtf8().data());
#endif

run();
});
thread = RustThread::spawn([=] { run(); }, name.toStdString());

w.wait(&m);
return (bool)worker;
Expand Down
Loading