Files
MultiThreading/main.cpp
2025-04-12 19:08:17 -04:00

62 lines
1.9 KiB
C++

#include <MultiThreading/Task.h>
#include <MultiThreading/Thread.h>
#include <MultiThreading/ThreadPool.h>
#include <iostream>
using namespace MultiThreading;
void cb() { std::cout << "hi" << std::endl; }
int32_t some_test_func(int32_t hello) {
for (unsigned int i = 0; i < 1000000000; i++) {}
std::cout << "task " << hello << " finishes." << std::endl;
return rand();
}
/*
int main() {
// Each task you create can be run by a thread only once. It's marked as complete after.
// If you're running a lambda or std::function directly on the thread, It can be used multiple times.
int32_t a = 0;
auto some_task = Task<int32_t>::Create([] { return some_test_func(4); }, &a);
// You can start threads in place like this, but you have to wait for the amount of time
// it takes for the thread to start up which in many cases is longer than the job. Use thread pool.
Thread some_thread;
//some_thread.SetTaskCompletionCallback(cb);
some_thread.SetTask(some_task);
//while (!some_task->Complete()) {}
//std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::cout << some_thread.Busy() << std::endl;
// Some work running concurrently with the worker thread.
//for (unsigned int i = 0; i < 10; i++) {}
// When we get to the point in our code where we need the result from the task wait until it's finished.
//while (!some_task->Complete()) {}
//std::cout << a << std::endl;
}
*/
int main() {
srand(time(nullptr));
int32_t task_completion_count = 0;
auto* thread_pool = new ThreadPool(16);
for (unsigned int i = 0; i < 128; i++) {
auto some_task = Task<int32_t>::Create(([i] { return some_test_func(i); }), cb, &task_completion_count);
thread_pool->Enqueue(some_task);
}
/// do stuff after the job.
delete thread_pool;
std::cout << "The returned random value was: " << task_completion_count << std::endl;
}