shared methods

unknown soldier unknownsoldier at gmail.com
Tue Jan 21 21:16:28 PST 2014


I'm confused by shared and how to use it.

import std.stdio;
class Foo {
     File logFile;
     void log(in string line) shared {
       synchronized(this){
         logFile.writeln(line);
       }
     }
}

This (or the equivalent code in my full size program) won't
compile:

source/log.d(256): Error: template std.stdio.File.writeln does
not match any function template declaration. Candidates are:
/usr/include/dmd/phobos/std/stdio.d(781):
std.stdio.File.writeln(S...)(S args)
source/log.d(256): Error: template std.stdio.File.writeln(S...)(S
args) cannot deduce template function from argument types
!()(const(immutable(char)[])) shared

Why is logFile suddenly being treated as shared? This does not
make sense to me. As a programmer I have acknowledged that log()
is a shared function in the declaration 'void log(in string line)
shared', so isn't it up to me to ensure that I do proper
synchronization within the function? Why is the compiler trying
to ensure that all functions called within log() are also marked
shared?
What is the right thing to do here?

Note that I can't just mark log() as not shared; log() must be
shared because elsewhere I have:

shared Foo sfoo = ...
sfoo.log(...)


More information about the Digitalmars-d-learn mailing list