Two things about shared

Benjamin Thaut code at benjamin-thaut.de
Fri Mar 25 12:38:34 PDT 2011


First thought:
Consider the following code:

import std.concurrency;

class Logger {
	void log(string msg){
		//do logging
	}
}

class ThreadsafeLogger : Logger {
private:
	Tid m_Tid;
public:
	this(){
		m_Tid = thisTid();
	}
	
	/// Returns: tid of owning process
	Tid getTid(){ return m_Tid; }
	
	//this should get called by any thread other then the owner
	void log(string msg) shared {
		send(getTid(),msg);
	}
	
	// this gets called by the owning thread every now and then
	void progressMessages(){
		receiveTimeout(0,
			(string msg){
				//this calles the non shared version
				this.log(msg);
			}
		);
	}
}

The idea behind is to use the functionality of the already implemented 
class for a call from the owning thread and pass messages for any 
threads accessing the functionally from outside of the owning thread 
into the owning thread. Unfortunately D prevents me from implementing it 
like this because it thinks I want to override log, which I cleary not 
want to do, which can be recognized from the shared attribute.
The only solution to solve this is to modifiy the original class, by 
adding a shared log function, which I wanted to prevent.
So would it be usefull to remove this compiler error? Or is there some 
problem connected to this I'm not seeing?

Second thought:

synchronized class main {
private:
	ILogger m_Logger;
	IGame m_Game;
public:
	void work(){
		//do something with m_Logger and m_Game
	}

	ILogger getLogger(){
		return m_Logger;
	}
}

In the above class both m_Logger and m_Game get the shared attribute. 
The shared attribute for the m_Logger variable is ok, because it can be 
queried from the class, and it could be used in other threads.
But the m_Game variable is completely encapsuled into the class and can 
only be used from within the class. As the synchronized prevents any 
paralell use of the class, it should be save to assume that m_Game never 
gets used by multiple threads simulatiously and does not need the shared 
attribute. What do you think about this? Is there some reason to not do 
this I'm not seeing?

-- 
Kind Regards
Benjamin Thaut


More information about the Digitalmars-d mailing list