Skip to content

Instantly share code, notes, and snippets.

@Clemapfel
Last active August 14, 2022 17:36
Show Gist options
  • Save Clemapfel/85ea905af7dcf1045f7aabec87810379 to your computer and use it in GitHub Desktop.
Save Clemapfel/85ea905af7dcf1045f7aabec87810379 to your computer and use it in GitHub Desktop.
#include <thread>
#include <chrono>
#include <jluna.hpp>
// references https://github.com/Clemapfel/jluna/issues/33
int main()
{
using namespace jluna;
initialize(2);
static auto sleep_jl = []() {
static auto* sleep_jl = unsafe::get_function(Main, "sleep"_sym);
unsafe::call(sleep_jl, box(0.1));
};
static auto sleep_cpp = [](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
};
static size_t n_runs = 5;
static auto run = [](bool worker_use_jl_wait, bool master_use_jl_wait)
{
size_t n_worker_runs = 0;
size_t n_master_runs = 0;
std::cout << "Worker: " << (worker_use_jl_wait ? "jl" : "cpp") << " | Master: " << (master_use_jl_wait ? "jl" : "cpp") << std::endl;
auto worker = [&]() {
while (n_worker_runs++ < n_runs)
{
std::cout << "worker" << std::endl;
if (worker_use_jl_wait)
sleep_jl();
else
sleep_cpp();
}
};
Task<void> task = ThreadPool::create<void()>(worker);
task.schedule();
while (n_master_runs++ < n_runs)
{
std::cout << "master" << std::endl;
if (master_use_jl_wait)
sleep_jl();
else
sleep_cpp();
}
task.join();
std::cout << std::endl;
};
for (bool b1 : {true, false})
for (bool b2 : {true, false})
run(b1, b2);
return 0;
}
// Sample output:
/*
[JULIA][LOG] initialization successful (2 thread(s)).
Worker: cpp | Master: cpp
main
worker
main
worker
main
worker
main
worker
main
worker
Worker: cpp | Master: jl
main
worker
main
worker
main
worker
main
main
worker
worker
Worker: jl | Master: jl
main
worker
main
main
main
main
worker
worker
worker
worker
Worker: jl | Master: cpp
main
worker
main
main
main
main
worker
worker
worker
worker
Process finished with exit code 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment