|
| 1 | +//! Multi threaded lua program |
| 2 | +//! The additional header must be passed to the build using `-Dlua_user_h=examples/user.h` |
| 3 | +//! Checkout http://lua-users.org/wiki/ThreadsTutorial for more info |
| 4 | + |
| 5 | +const std = @import("std"); |
| 6 | +const zlua = @import("zlua"); |
| 7 | + |
| 8 | +var mutex = std.Thread.Mutex{}; |
| 9 | + |
| 10 | +export fn lua_zlock(L: *zlua.LuaState) callconv(.C) void { |
| 11 | + _ = L; |
| 12 | + mutex.lock(); |
| 13 | +} |
| 14 | + |
| 15 | +export fn lua_zunlock(L: *zlua.LuaState) callconv(.C) void { |
| 16 | + _ = L; |
| 17 | + mutex.unlock(); |
| 18 | +} |
| 19 | + |
| 20 | +fn add_to_x(lua: *zlua.Lua, num: usize) void { |
| 21 | + for (0..num) |_| { |
| 22 | + // omit error handling for brevity |
| 23 | + lua.loadString("x = x + 1\n") catch return; |
| 24 | + lua.protectedCall(.{}) catch return; |
| 25 | + } |
| 26 | + |
| 27 | + const size = 256; |
| 28 | + var buf = [_:0]u8{0} ** size; |
| 29 | + _ = std.fmt.bufPrint(&buf, "print(\"{}: \", x)", .{std.Thread.getCurrentId()}) catch return; |
| 30 | + |
| 31 | + // The printing from different threads does not always work nicely |
| 32 | + // There seems to be a separate sterr lock on each argument to print |
| 33 | + lua.loadString(&buf) catch return; |
| 34 | + lua.protectedCall(.{}) catch return; |
| 35 | +} |
| 36 | + |
| 37 | +pub fn main() anyerror!void { |
| 38 | + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; |
| 39 | + const allocator = gpa.allocator(); |
| 40 | + defer _ = gpa.deinit(); |
| 41 | + |
| 42 | + // Initialize The Lua vm and get a reference to the main thread |
| 43 | + var lua = try zlua.Lua.init(allocator); |
| 44 | + defer lua.deinit(); |
| 45 | + |
| 46 | + lua.openLibs(); |
| 47 | + |
| 48 | + // create a global variable accessible by all threads |
| 49 | + // omit error handling for brevity |
| 50 | + try lua.loadString("_G.x = 0\n"); |
| 51 | + try lua.protectedCall(.{}); |
| 52 | + |
| 53 | + const num = 1_000; |
| 54 | + const n_jobs = 5; |
| 55 | + var subs: [n_jobs]*zlua.Lua = undefined; |
| 56 | + |
| 57 | + // create a thread pool to run all the functions |
| 58 | + var pool: std.Thread.Pool = undefined; |
| 59 | + try pool.init(.{ .allocator = allocator, .n_jobs = n_jobs }); |
| 60 | + defer pool.deinit(); |
| 61 | + |
| 62 | + var wg: std.Thread.WaitGroup = .{}; |
| 63 | + |
| 64 | + for (0..n_jobs) |i| { |
| 65 | + subs[i] = lua.newThread(); |
| 66 | + pool.spawnWg(&wg, add_to_x, .{ subs[i], num }); |
| 67 | + } |
| 68 | + |
| 69 | + // also do the thing from the main thread |
| 70 | + add_to_x(lua, num); |
| 71 | + |
| 72 | + wg.wait(); |
| 73 | + |
| 74 | + for (subs) |sub| { |
| 75 | + try lua.closeThread(sub); |
| 76 | + } |
| 77 | + |
| 78 | + // print the final value |
| 79 | + try lua.loadString("print(x)\n"); |
| 80 | + try lua.protectedCall(.{}); |
| 81 | +} |
0 commit comments