threads.zig (1479B)
1 const std = @import("std"); 2 const pi = @import("pi"); 3 4 const interrupts = pi.interrupts; 5 const uart = pi.devices.mini_uart; 6 const clock = pi.devices.clock; 7 const timer = pi.devices.timer; 8 const thread = pi.thread; 9 const mem = pi.mem; 10 11 fn thread_test(arg: ?*anyopaque) callconv(.c) void { 12 _ = arg; 13 14 var count: usize = 0; 15 16 while (true) { 17 // Don't use format for simpler function 18 const cs = mem.enter_critical_section(); 19 20 uart.write_slice_sync("tid = "); 21 uart.write_byte_sync(@truncate(thread.get_tid() + 48)); 22 uart.write_byte_sync('\n'); 23 24 count += 1; 25 26 cs.exit(); 27 28 if (count > 1024) break; 29 } 30 } 31 32 noinline fn tick(regs: interrupts.Registers) void { 33 if (!thread.is_ready()) return; 34 35 uart.print("preempting PC=0x{X}\n", .{regs.pc}); 36 thread.preempt(®s); 37 } 38 39 pub fn main() !void { 40 var buffer: [1024 * 1024]u8 = undefined; 41 var fba: std.heap.FixedBufferAllocator = .init(&buffer); 42 43 try thread.init(fba.allocator()); 44 45 try thread.fork(thread_test, null); 46 try thread.fork(thread_test, null); 47 try thread.fork(thread_test, null); 48 try thread.fork(thread_test, null); 49 50 uart.print("Forked threads\n", .{}); 51 52 timer.set_tick(tick); 53 uart.print("Setting tick\n", .{}); 54 55 timer.initialize(.Sixteen, 0x32); 56 57 uart.print("Timer Initialized\n", .{}); 58 59 uart.print("Joining\n", .{}); 60 61 try thread.join(); 62 63 uart.print("Done!\n", .{}); 64 65 while (true) {} 66 }