| 1 |
/* ThreadManager.vala |
| 2 |
* |
| 3 |
* Copyright 2023 Diego Iván <[email protected]> |
| 4 |
* |
| 5 |
* SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace ThreadManager { |
| 9 |
private static ThreadPool<Task> thread_pool; |
| 10 |
private static bool initiated = false; |
| 11 |
private static bool supported = true; |
| 12 |
|
| 13 |
public delegate G ThreadFunc<G> () throws Error; |
| 14 |
public delegate void TaskFunc (); |
| 15 |
|
| 16 |
[Compact] |
| 17 |
private class Task { |
| 18 |
public TaskFunc task_func; |
| 19 |
|
| 20 |
public Task (owned TaskFunc task_func_) { |
| 21 |
task_func = (owned) task_func_; |
| 22 |
} |
| 23 |
|
| 24 |
public void run () { |
| 25 |
task_func (); |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
private void init () { |
| 30 |
if (initiated) { |
| 31 |
return; |
| 32 |
} |
| 33 |
|
| 34 |
try { |
| 35 |
thread_pool = new ThreadPool<Task>.with_owned_data (run_task, 1, false); |
| 36 |
} |
| 37 |
catch (Error e) { |
| 38 |
supported = false; |
| 39 |
critical (e.message); |
| 40 |
} |
| 41 |
|
| 42 |
initiated = true; |
| 43 |
} |
| 44 |
|
| 45 |
private void run_task (owned Task task) { |
| 46 |
task.run (); |
| 47 |
} |
| 48 |
|
| 49 |
public async G run_in_thread<G> (owned ThreadFunc<G> thread_func) throws Error { |
| 50 |
if (!initiated) { |
| 51 |
init (); |
| 52 |
} |
| 53 |
|
| 54 |
if (!supported) { |
| 55 |
critical ("Thread Creation not supported in this context. Running synchronously..."); |
| 56 |
return thread_func (); |
| 57 |
} |
| 58 |
|
| 59 |
Error? error = null; |
| 60 |
G retval = null; |
| 61 |
|
| 62 |
thread_pool.add (new Task (() => { |
| 63 |
try { |
| 64 |
retval = thread_func (); |
| 65 |
} |
| 66 |
catch (Error e) { |
| 67 |
error = e; |
| 68 |
} |
| 69 |
Idle.add (run_in_thread.callback); |
| 70 |
})); |
| 71 |
|
| 72 |
yield; |
| 73 |
|
| 74 |
if (error != null) { |
| 75 |
throw error; |
| 76 |
} |
| 77 |
|
| 78 |
return retval; |
| 79 |
} |
| 80 |
} |