Reputation: 521
Given the following snippet, does the call to unlock occur after the break or before?
var input_data: InputState = blk: {
user.input_mutex.lock();
defer user.input_mutex.unlock();
break :blk user.input;
};
Upvotes: 3
Views: 919
Reputation: 6486
The documentation says:
defer will execute an expression at the end of the current scope.
It's not worded very clearly, but it means that the defer
statements are executed after all of the code in the current block has been executed. This includes break
statements.
For example, an errdefer
statement cannot be executed before the last line, because errdefer
statements are only enabled after return error.SomeError
, which would be the last line in a function.
Upvotes: 4
Reputation: 521
Yes, at least as of zig version 0.12.0-dev.167+dd6a9caea
Running the following snippet:
const std = @import("std");
fn getRandom() !u64 {
var seed: u64 = undefined;
try std.os.getrandom(std.mem.asBytes(&seed));
std.debug.print("test seed: {}\n", .{seed});
return seed;
}
pub fn main() !void {
var value = blk: {
defer std.debug.print("defer test seed\n", .{});
break :blk try getRandom();
};
_ = value;
}
Will show the following in console output:
test seed: 6866361107008308078
defer test seed
Upvotes: 1