Skip to content

Instantly share code, notes, and snippets.

View kprotty's full-sized avatar

protty kprotty

View GitHub Profile
@kprotty
kprotty / sync.rs
Last active March 20, 2024 16:11
mod futex {
use std::{sync::atomic::AtomicU32, time::Duration};
pub fn wait(_ptr: &AtomicU32, _cmp: u32, _timeout: Option<Duration>) -> bool {
unimplemented!("TODO")
}
pub fn wake(_ptr: *const AtomicU32, _max_wake: u32) {
unimplemented!("TODO")
}
@kprotty
kprotty / sync.go
Last active March 20, 2024 16:11
Crossplatfomr futex and rwlock for Go
package main
import (
"sync/atomic"
"unsafe"
)
type mutex struct {
key uintptr
}
unlocked = 0
readers_parked = 1 << 0
writers_parked = 1 << 1
value = 1 << 2
mask = ~(value - 1)
reader = value
writer = mask
const std = @import("std");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(gpa.deinit());
const allocator = &gpa.allocator;
const num_threads = std.math.max(1, (std.Thread.getCpuCount() catch 1) / 2);
const epolls = try allocator.alloc(std.os.fd_t, num_threads);
defer allocator.free(epolls);
use std::{
cell::{Cell, UnsafeCell},
pin::Pin,
time::Instant,
};
pub(crate) struct Lock<T> {
os_lock: os::OsLock,
value: UnsafeCell<T>,
}
@kprotty
kprotty / event.zig
Last active March 20, 2024 16:11
One-file event loop
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const Loop = struct {
io_poller: IoPoller,
allocator: *Allocator,
is_running: bool = true,
is_notifying: bool = false,
run_queue: RunQueue = .{},
spawned_threads: usize = 0,
@kprotty
kprotty / Loop.zig
Last active March 20, 2024 16:11
Base for next event loop
const std = @import("std");
const Loop = @This();
counter: usize = 0,
stack_size: usize,
max_workers: usize,
idle_lock: Lock = .{},
idle_workers: ?*Worker = null,
spawned_workers: ?*Worker = null,
run_queues: [Priority.ARRAY_SIZE]GlobalQueue = [_]GlobalQueue{.{}} ** Priority.ARRAY_SIZE,
@kprotty
kprotty / AutoResetEvent.cfg
Last active January 11, 2021 02:05
Formally proving the correctness of synchronization primitives
INIT Init
NEXT Next
CONSTANT Setters = 3
INVARIANTS
IsEventuallySet
NoWaiterDeadlock
use std::{
pin::Pin,
future::Future,
cell::UnsafeCell,
task::{Waker, RawWaker, RawWakerVTable, Poll, Context},
sync::atomic::{AtomicUsize, Ordering},
};
struct VTable {
resume: unsafe fn(*const Task),
@kprotty
kprotty / ThreadPool.zig
Last active March 20, 2024 16:12
An isolated thread pool implementation for Zig
const std = @import("std");
const system = std.os.system;
pub const Scheduler = struct {
pub const InitConfig = struct {
max_threads: ?u16 = null,
};
pub fn init(self: *Scheduler, config: InitConfig) !void {