Skip to content

Instantly share code, notes, and snippets.

@jordywastaken
Last active December 18, 2022 14:57
Show Gist options
  • Save jordywastaken/d4818080d83bdaa2ac10c159b063c10b to your computer and use it in GitHub Desktop.
Save jordywastaken/d4818080d83bdaa2ac10c159b063c10b to your computer and use it in GitHub Desktop.
PlayStation 3 thread wrapper
#pragma once
#include <sys/ppu_thread.h>
class Thread
{
private:
class ThreadArg
{
public:
void(*callback)(void*);
void* userData;
};
public:
Thread() = default;
Thread(void(*callback)(void*), void* userData, int priority = 1000, int stackSize = 2048, const char* name = "", int flag = SYS_PPU_THREAD_CREATE_JOINABLE)
{
ThreadArg* argument = new ThreadArg();
argument->callback = callback;
argument->userData = userData;
int ret = sys_ppu_thread_create(&id, [](uint64_t arg) -> void
{
ThreadArg* argument = reinterpret_cast<ThreadArg*>((uint32_t)arg);
if (argument)
{
if (argument->callback)
argument->callback(argument->userData);
delete argument;
}
sys_ppu_thread_exit(0);
}, reinterpret_cast<uint64_t>(argument), priority, stackSize, flag, name);
if (ret != CELL_OK)
delete argument;
}
Thread(void(*callback)(), int priority = 1000, int stackSize = 2048, const char* name = "", int flag = SYS_PPU_THREAD_CREATE_JOINABLE)
{
sys_ppu_thread_create(&id, [](uint64_t arg) -> void
{
if (arg)
reinterpret_cast<void(*)()>((uint32_t)arg)();
sys_ppu_thread_exit(0);
}, reinterpret_cast<uint64_t>(callback), priority, stackSize, flag, name);
}
bool IsStarted()
{
return (id != SYS_PPU_THREAD_ID_INVALID);
}
bool Join()
{
if (!IsStarted())
return false;
uint64_t exitCode;
return sys_ppu_thread_join(id, &exitCode) == CELL_OK;
}
void Rename(const char* name)
{
if (IsStarted())
sys_ppu_thread_rename(id, name);
}
sys_ppu_thread_t id = SYS_PPU_THREAD_ID_INVALID;
};
/*
* Usage:
*
* Thread example = Thread([]
* {
* printf("Hello from a thread with no argument!\n");
* });
*
* OR
*
* int exampleData = 21;
* Thread example = Thread([](void* userData)
* {
* printf("Hello from a thread with an argument! User data: %i\n", *(int*)userData);
* }, &exampleData);
*
*
*
* example.Join();
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment