log: implement set_always_flush/1 for log.Log, log.ThreadSafeLog and log.Logger#20698
log: implement set_always_flush/1 for log.Log, log.ThreadSafeLog and log.Logger#20698spytheman merged 3 commits intovlang:masterfrom
Conversation
| pub fn (mut x ThreadSafeLog) set_always_flush(should_flush bool) { | ||
| x.mu.@lock() | ||
| x.Log.set_always_flush(should_flush) | ||
| x.mu.unlock() |
There was a problem hiding this comment.
Shouldn't this be a defer x.mu.unlock()?
There was a problem hiding this comment.
Shouldn't this be a
defer x.mu.unlock()?
why? there no 2 return's anyway
There was a problem hiding this comment.
The execution of the function doesn't happen linearly when concurrency is used. defer fixes that here.
There was a problem hiding this comment.
The execution of the function doesn't happen linearly when concurrency is used.
deferfixes that here.
- Current version:
import sync
struct Abc {
mut:
mu sync.Mutex
}
fn (mut x Abc) f() {
x.mu.@lock()
println('foo')
x.mu.unlock()
}
fn main() {
mut y := Abc{}
y.f()
}C output:
void main__Abc_f(main__Abc* x) {
sync__Mutex_lock(&x->mu);
println(_SLIT("foo"));
sync__Mutex_unlock(&x->mu);
}- Your version:
fn (mut x Abc) f() {
x.mu.@lock()
defer { x.mu.unlock() }
println('foo')
}Output:
void main__Abc_f(main__Abc* x) {
bool main__Abc_f_defer_0 = false;
sync__Mutex_lock(&x->mu);
main__Abc_f_defer_0 = true;
println(_SLIT("foo"));
// Defer begin
if (main__Abc_f_defer_0) {
sync__Mutex_unlock(&x->mu);
}
// Defer end
}There was a problem hiding this comment.
The execution of the function doesn't happen linearly when concurrency is used. defer fixes that here.
No, it happens in order. The mutex lock and unlock are here, to protect multiple threads from executing the code in between them. They ensure that only one thread (the one that succeed in locking the mutex), will continue. All the other will block.
Then one of the other threads will continue, while others continue to block etc.
I am not using defer here, since that will use 3 lines for the defer block, not just 1, and since the body is a single line -> I think that the version with defer will be less clear to read.
No description provided.