Skip to main content

webp/utils/
thread_utils.rs

1// libwebp v1.6.0, src/utils/thread_utils.c:
2//
3// Copyright 2011 Google Inc. All Rights Reserved.
4//
5// Use of this source code is governed by a BSD-style license
6// that can be found in the COPYING file in the root of the source
7// tree. An additional intellectual property rights grant can be found
8// in the file PATENTS. All contributing project authors may
9// be found in the AUTHORS file in the root of the source tree.
10// -----------------------------------------------------------------------------
11//
12// Multi-threaded worker
13//
14// Author: Skal (pascal.massimino@gmail.com)
15
16// libwebp v1.6.0, src/utils/thread_utils.h:
17//
18// Copyright 2011 Google Inc. All Rights Reserved.
19//
20// Use of this source code is governed by a BSD-style license
21// that can be found in the COPYING file in the root of the source
22// tree. An additional intellectual property rights grant can be found
23// in the file PATENTS. All contributing project authors may
24// be found in the AUTHORS file in the root of the source tree.
25// -----------------------------------------------------------------------------
26//
27// Multi-threaded worker
28//
29// Author: Skal (pascal.massimino@gmail.com)
30
31//! Translation of `src/utils/thread_utils.c` and `src/utils/thread_utils.h` from libwebp v1.6.0.
32//!
33//! Work package: WP1 (types, memory, workers).
34//!
35//! `WebPWorkerInterface`, `WebPSetWorkerInterface` and `WebPGetWorkerInterface`
36//! are not translated (ADR 0003, decided 2026-11-06). Callers use the worker
37//! methods directly, and no public header declares the replacement table.
38//!
39//! Every worker starts a `std::thread` on `reset`, as the reference configuration
40//! with `WEBP_USE_THREAD` does. The thread and the caller share one `Mutex` with
41//! one `Condvar`. The job (hook and two data values) moves to the thread at
42//! `launch` and comes back at `sync` or `end`; while the worker is working, the
43//! caller has no access to the data, which the borrow checker enforces.
44//!
45//! # Deviations from upstream
46//!
47//! Changes of representation that the ADRs allow, or behavior that the Rust
48//! side cannot reproduce exactly. Each records the reason.
49//!
50//! 1. **Worker allocation.** The shared synchronization object is allocated in
51//!    `WebPWorker::init` (C: `Init`) rather than in `Reset`, so a failed
52//!    allocation cannot make `Reset` return `false`. A failed spawn still does:
53//!    `Reset` returns `false` and the status stays `NOT_OK`, as ADR 0003
54//!    requires.
55
56use std::cmp::Ordering;
57use std::panic::{self, AssertUnwindSafe};
58use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
59use std::thread::JoinHandle;
60
61// upstream: src/utils/thread_utils.h WebPWorkerStatus
62/// State of a worker (C: `WebPWorkerStatus`); the values keep the C order.
63#[repr(transparent)]
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
65pub struct WebPWorkerStatus(pub u32);
66
67impl WebPWorkerStatus {
68    // upstream: src/utils/thread_utils.h NOT_OK
69    pub const NOT_OK: Self = Self(0);
70    // upstream: src/utils/thread_utils.h OK
71    pub const OK: Self = Self(1);
72    // upstream: src/utils/thread_utils.h WORK
73    pub const WORK: Self = Self(2);
74}
75
76// upstream: src/utils/thread_utils.h WebPWorkerHook
77/// The function a worker runs on its two data values. It returns `false` on
78/// error (C: `WebPWorkerHook`, which returns `int`).
79pub type WebPWorkerHook<D1, D2> = fn(&mut D1, &mut D2) -> bool;
80
81/// The hook and the data that it runs on.
82struct Job<D1, D2> {
83    hook: WebPWorkerHook<D1, D2>,
84    data1: D1,
85    data2: D2,
86}
87
88/// The state that the caller and the thread share (C: the fields of `WebPWorker`
89/// that `ThreadLoop` reads and writes under the mutex).
90struct State<D1, D2> {
91    status: WebPWorkerStatus,
92    had_error: bool,
93    /// The job while the worker is working; the caller takes it back at `sync`.
94    job: Option<Job<D1, D2>>,
95}
96
97/// The mutex, the condition and the state that a worker thread shares (C:
98/// `WebPWorkerImpl`, plus the status fields of `WebPWorker`).
99struct Shared<D1, D2> {
100    state: Mutex<State<D1, D2>>,
101    changed: Condvar,
102}
103
104impl<D1, D2> Shared<D1, D2> {
105    fn lock(&self) -> MutexGuard<'_, State<D1, D2>> {
106        self.state.lock().unwrap_or_else(PoisonError::into_inner)
107    }
108
109    fn wait<'a>(&self, guard: MutexGuard<'a, State<D1, D2>>) -> MutexGuard<'a, State<D1, D2>> {
110        self.changed
111            .wait(guard)
112            .unwrap_or_else(PoisonError::into_inner)
113    }
114}
115
116/// Moves a job that the thread returned back into the worker.
117fn return_job<D1, D2>(job: &mut Option<Job<D1, D2>>, state: &mut State<D1, D2>) {
118    if let Some(returned) = state.job.take() {
119        *job = Some(returned);
120    }
121}
122
123// upstream: src/utils/thread_utils.h WebPWorker
124/// A worker that runs one hook on its job, on a thread or on the caller's
125/// thread (C: `WebPWorker`).
126pub struct WebPWorker<D1, D2> {
127    /// The hook and data while the worker is idle; the thread holds them while
128    /// the worker works (C: the `hook`, `data1` and `data2` fields).
129    job: Option<Job<D1, D2>>,
130    shared: Arc<Shared<D1, D2>>,
131    /// Present after a successful `reset`, until `end` (C: `impl != NULL`).
132    thread: Option<JoinHandle<()>>,
133    /// True from `launch` until `sync` or `end` return the job.
134    working: bool,
135}
136
137// upstream: src/utils/thread_utils.c Init
138impl<D1, D2> Default for WebPWorker<D1, D2> {
139    fn default() -> Self {
140        Self::init()
141    }
142}
143
144impl<D1, D2> WebPWorker<D1, D2> {
145    // upstream: src/utils/thread_utils.c Init
146    /// Creates an idle worker with no job and no thread (C: `Init`).
147    #[must_use]
148    pub fn init() -> Self {
149        Self {
150            job: None,
151            shared: Arc::new(Shared {
152                state: Mutex::new(State {
153                    status: WebPWorkerStatus::NOT_OK,
154                    had_error: false,
155                    job: None,
156                }),
157                changed: Condvar::new(),
158            }),
159            thread: None,
160            working: false,
161        }
162    }
163
164    // upstream: src/utils/thread_utils.h WebPWorker
165    /// Sets the hook and the data that the next `launch` or `execute` runs (C:
166    /// setting `hook`, `data1` and `data2`).
167    ///
168    /// # Panics
169    ///
170    /// Panics while the worker is working: C forbids the change until `sync`.
171    pub fn set_job(&mut self, hook: WebPWorkerHook<D1, D2>, data1: D1, data2: D2) {
172        assert!(
173            !self.working,
174            "the job of a working worker belongs to its thread until sync"
175        );
176        self.job = Some(Job { hook, data1, data2 });
177    }
178
179    /// The data of the current job; `None` when there is no job or the worker
180    /// is working, because the thread then owns the data.
181    #[must_use]
182    pub fn job_data(&self) -> Option<(&D1, &D2)> {
183        self.job.as_ref().map(|job| (&job.data1, &job.data2))
184    }
185
186    /// Mutable access to the data of the current job, under the same rule as
187    /// [`WebPWorker::job_data`].
188    pub fn job_data_mut(&mut self) -> Option<(&mut D1, &mut D2)> {
189        self.job
190            .as_mut()
191            .map(|job| (&mut job.data1, &mut job.data2))
192    }
193
194    // upstream: src/utils/thread_utils.h WebPWorker
195    /// The current status (C: the `status` field).
196    #[must_use]
197    pub fn status(&self) -> WebPWorkerStatus {
198        self.shared.lock().status
199    }
200
201    /// Whether the hook has failed since the last `reset` (C: the `had_error`
202    /// field).
203    #[must_use]
204    pub fn had_error(&self) -> bool {
205        self.shared.lock().had_error
206    }
207
208    // upstream: src/utils/thread_utils.c Execute
209    /// Runs the hook on the calling thread and records a failure (C: `Execute`).
210    /// A worker without a job does nothing.
211    pub fn execute(&mut self) {
212        if let Some(job) = self.job.as_mut()
213            && !(job.hook)(&mut job.data1, &mut job.data2)
214        {
215            self.shared.lock().had_error = true;
216        }
217    }
218
219    // upstream: src/utils/thread_utils.c ChangeState
220    /// Waits until the worker is idle and moves it to `new_status` when that is
221    /// not `OK` (C: `ChangeState`). Without a thread this does nothing.
222    fn change_state(&mut self, new_status: WebPWorkerStatus) {
223        if self.thread.is_none() {
224            return;
225        }
226        let mut state = self.shared.lock();
227        if state.status >= WebPWorkerStatus::OK {
228            while state.status != WebPWorkerStatus::OK {
229                state = self.shared.wait(state);
230            }
231            if new_status != WebPWorkerStatus::OK {
232                state.status = new_status;
233                drop(state);
234                self.shared.changed.notify_all();
235            }
236        }
237    }
238
239    // upstream: src/utils/thread_utils.c Launch
240    /// Starts the job on the thread (C: `Launch`). Without a thread nothing
241    /// starts and the hook does not run, as in C.
242    pub fn launch(&mut self) {
243        if self.thread.is_none() {
244            return;
245        }
246        let mut state = self.shared.lock();
247        if state.status >= WebPWorkerStatus::OK {
248            while state.status != WebPWorkerStatus::OK {
249                state = self.shared.wait(state);
250            }
251            return_job(&mut self.job, &mut state);
252            state.status = WebPWorkerStatus::WORK;
253            state.job = self.job.take();
254            self.working = true;
255            drop(state);
256            self.shared.changed.notify_all();
257        }
258    }
259
260    // upstream: src/utils/thread_utils.c Sync
261    /// Waits until the worker is idle, takes the job back and reports whether no
262    /// hook has failed (C: `Sync`). Without a thread the job never left the
263    /// worker, so this only reports the error flag.
264    #[must_use]
265    pub fn sync(&mut self) -> bool {
266        self.change_state(WebPWorkerStatus::OK);
267        let mut state = self.shared.lock();
268        debug_assert!(state.status <= WebPWorkerStatus::OK);
269        return_job(&mut self.job, &mut state);
270        self.working = false;
271        !state.had_error
272    }
273
274    // upstream: src/utils/thread_utils.c End
275    /// Stops the thread and takes the job back (C: `End`). A worker without a
276    /// thread is left as it is.
277    pub fn end(&mut self) {
278        if self.thread.is_none() {
279            return;
280        }
281        self.change_state(WebPWorkerStatus::NOT_OK);
282        if let Some(handle) = self.thread.take() {
283            // The thread has finished its loop; joining only reaps it.
284            let _ = handle.join();
285        }
286        let mut state = self.shared.lock();
287        return_job(&mut self.job, &mut state);
288        self.working = false;
289    }
290}
291
292impl<D1: Send + 'static, D2: Send + 'static> WebPWorker<D1, D2> {
293    // upstream: src/utils/thread_utils.c Reset
294    /// Starts the worker thread when the worker is idle, or syncs it when it is
295    /// working. Clears the error flag first, as C does. Returns `false` when no
296    /// thread can be started; the status then stays `NOT_OK` (C: `Reset`).
297    #[must_use]
298    pub fn reset(&mut self) -> bool {
299        let mut state = self.shared.lock();
300        state.had_error = false;
301        match state.status.cmp(&WebPWorkerStatus::OK) {
302            Ordering::Less => {
303                // The lock stays held while the thread starts, as in C, so the new
304                // thread sees the `OK` status when it first takes the lock.
305                state.status = WebPWorkerStatus::OK;
306                let shared = Arc::clone(&self.shared);
307                if let Ok(handle) = std::thread::Builder::new().spawn(move || thread_loop(&shared))
308                {
309                    self.thread = Some(handle);
310                    true
311                } else {
312                    state.status = WebPWorkerStatus::NOT_OK;
313                    false
314                }
315            }
316            Ordering::Greater => {
317                drop(state);
318                self.sync()
319            }
320            Ordering::Equal => true,
321        }
322    }
323}
324
325impl<D1, D2> Drop for WebPWorker<D1, D2> {
326    fn drop(&mut self) {
327        // C leaves the thread running unless the caller calls `End`; the Rust
328        // worker ends it so that dropping a worker never leaks a thread.
329        self.end();
330    }
331}
332
333/// Runs the hook of the job in `state`, recording a failure (C: `Execute` on the
334/// thread). A panicking hook counts as a failed hook, so that `sync` returns
335/// instead of waiting for a status that never arrives.
336// upstream: src/utils/thread_utils.c Execute
337fn run_job<D1, D2>(state: &mut State<D1, D2>) {
338    let State { had_error, job, .. } = state;
339    let Some(job) = job.as_mut() else {
340        return;
341    };
342    let ok = panic::catch_unwind(AssertUnwindSafe(|| {
343        (job.hook)(&mut job.data1, &mut job.data2)
344    }))
345    .unwrap_or(false);
346    if !ok {
347        *had_error = true;
348    }
349}
350
351// upstream: src/utils/thread_utils.c ThreadLoop
352/// The loop of a worker thread: it waits while the worker is idle, runs the job
353/// when the status is `WORK`, and returns when the status is `NOT_OK`.
354fn thread_loop<D1, D2>(shared: &Shared<D1, D2>) {
355    let mut done = false;
356    while !done {
357        let mut state = shared.lock();
358        while state.status == WebPWorkerStatus::OK {
359            state = shared.wait(state);
360        }
361        if state.status == WebPWorkerStatus::WORK {
362            run_job(&mut state);
363            state.status = WebPWorkerStatus::OK;
364        } else if state.status == WebPWorkerStatus::NOT_OK {
365            done = true;
366        }
367        drop(state);
368        shared.changed.notify_all();
369    }
370}