Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Dec 19th, 2005, 12:55 PM   #11
Jason Isom
Programmer
 
Join Date: Dec 2005
Posts: 53
Rep Power: 3 Jason Isom is on a distinguished road
I was hoping I could get your example to run into synchronization issues, but it outputted 48,000 lines without any synchronization issues. I'm relatively new to threading, although I do understand the theory behind it. I imagine I couldn't get it to throw an exception is because the operations are so simple.

However, all you have to do is surround your critical sections with lock(this) and you'll be set. It just hides all the implementation details of managing your own binary mutexes so that you don't have to do it yourself.

I apologize in advance if you already found a solution.

class Program
{
    StreamWriter sw = new StreamWriter("test.txt");
    public void methodA()
    {
        while (true)
        {
            p();
        }
    }

    public void methodB()
    {
        while (true)
        {
            p();
        }
    }

    public void p()
    {
        lock (this)
        {
            try
            {
                sw.WriteLine(Thread.CurrentThread.Name);
                Console.WriteLine(Thread.CurrentThread.Name);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.Message);
            }
        }
    }

    public void a()
    {
        Thread objThreadA = new Thread(new ThreadStart(methodA));
        objThreadA.Name = "A-Thread";
        objThreadA.Start();

        Thread objThreadB = new Thread(new ThreadStart(methodB));
        objThreadB.Name = "B-Thread";
        objThreadB.Start();
    }
    static void Main(string[] args)
    {
        Program p = new Program();
        p.a();
    }
}
Jason Isom is offline   Reply With Quote
Old Dec 19th, 2005, 1:02 PM   #12
para
Programmer
 
Join Date: Dec 2005
Posts: 65
Rep Power: 3 para is on a distinguished road
This may be a useful resource: http://msdn.microsoft.com/library/de...cpconMutex.asp
para is offline   Reply With Quote
Old Dec 19th, 2005, 1:08 PM   #13
MBirchmeier
Hobbyist Programmer
 
Join Date: Oct 2005
Posts: 211
Rep Power: 4 MBirchmeier is on a distinguished road
Quote:
Originally Posted by Jason Isom
I was hoping I could get your example to run into synchronization issues, but it outputted 48,000 lines without any synchronization issues. I'm relatively new to threading, although I do understand the theory behind it. I imagine I couldn't get it to throw an exception is because the operations are so simple.

However, all you have to do is surround your critical sections with lock(this) and you'll be set. It just hides all the implementation details of managing your own binary mutexes so that you don't have to do it yourself.

I apologize in advance if you already found a solution.
By the way : Good first post.

This is a good solution. I generally prefer to use mutexes instead of locks, but only to gaurentee(sp?) that any other functions or derived functions using the 'lock' will honor the locking routine. The resulting code would be

    public void p()
    {
        someMutex.WaitOne();
        try
        {
            sw.WriteLine(Thread.CurrentThread.Name);
            Console.WriteLine(Thread.CurrentThread.Name);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.Write(ex.Message);
        }
        someMutex.ReleaseMutex();       
    }

this way if p is made a virtual function, and a class overrides it it can simply lock the 'someMutex' object and proceed normally.

-MBirchmeier
MBirchmeier is offline   Reply With Quote
Old Dec 21st, 2005, 7:59 PM   #14
myName
Programmer
 
Join Date: Oct 2005
Posts: 48
Rep Power: 0 myName is on a distinguished road
mutex is added to the method p(someMessage). Now in testing state.
public void methodA()
{
	while( true )
	{
		...
		p( someMessage );
		Thread.Sleep(1000);
	}
}
		
public void methodB()
{
	while( true )
	{
		...
		p( someMessage );

		Thread.Sleep(1000);
	}
}

public void p( string someMessage)
{
       mut = new Mutex();
       someMutex.WaitOne();
        try
        {
            //Process write someMessage to File
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.Write(ex.Message);
        }
        someMutex.ReleaseMutex();       
}

public void a()
{
	Thread objThreadA = new Thread( new ThreadStart( methodA) );
	objThreadA.Start();

	Thread objThreadB = new Thread( new ThreadStart( methodB) );
	objThreadB.Start();
}

Last edited by myName; Dec 21st, 2005 at 8:18 PM.
myName is offline   Reply With Quote
Old Dec 21st, 2005, 8:36 PM   #15
The Dark
Expert Programmer
 
Join Date: Jun 2005
Posts: 882
Rep Power: 4 The Dark is on a distinguished road
Quote:
Originally Posted by myName
mutex is added to the method p(someMessage). Now in testing state.
public void methodA()
{
	while( true )
	{
		...
		p( someMessage );
		Thread.Sleep(1000);
	}
}
		
public void methodB()
{
	while( true )
	{
		...
		p( someMessage );

		Thread.Sleep(1000);
	}
}

public void p( string someMessage)
{
       mut = new Mutex();
       someMutex.WaitOne();
        try
        {
            //Process write someMessage to File
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.Write(ex.Message);
        }
        someMutex.ReleaseMutex();       
}

public void a()
{
	Thread objThreadA = new Thread( new ThreadStart( methodA) );
	objThreadA.Start();

	Thread objThreadB = new Thread( new ThreadStart( methodB) );
	objThreadB.Start();
}
What is this line doing in p()?
       mut = new Mutex();
It is creating a new mutex for each time you output an error, but then never using it. You should remove this line. I assume someMutex is declared and created elsewhere.
The Dark is offline   Reply With Quote
Old Dec 21st, 2005, 8:40 PM   #16
Dameon
Troll
 
Dameon's Avatar
 
Join Date: Apr 2005
Location: Texas
Posts: 732
Rep Power: 4 Dameon is on a distinguished road
TheDark is right. You need to have a mutex called someMutex (note the use of someMutex.WaitOne and ReleaseMutex) as a member of the class. Not a local variable, a member of the class. The point of a mutex is for both threads to access the same one (only one thread would be able to touch the local one) so that WaitOne blocks until ReleaseMutex is called.
__________________
MD5(sig) = bcef75433db02e9ad9bf81d6f7c5c270
Dameon is offline   Reply With Quote
Old Dec 21st, 2005, 9:58 PM   #17
Animatronic
Programmer
 
Join Date: Jun 2005
Posts: 99
Rep Power: 4 Animatronic is on a distinguished road
There is a synchronised attribute in c# equivalent to Java's keyword:

[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
(without the random spaces)

and is the same as doing a lock(this) around the entire conents of the method.
Animatronic is offline   Reply With Quote
Old Dec 22nd, 2005, 3:12 AM   #18
myName
Programmer
 
Join Date: Oct 2005
Posts: 48
Rep Power: 0 myName is on a distinguished road
I change to this.

private static Mutex mut;

public void p( string someMessage)
{
       if( someMutex == null )
            someMutex = new Mutex();

       someMutex.WaitOne();
        try
        {
            //Process write someMessage to File
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.Write(ex.Message);
        }
        someMutex.ReleaseMutex();       
}

Last edited by myName; Dec 22nd, 2005 at 3:31 AM.
myName is offline   Reply With Quote
Old Jan 16th, 2006, 1:40 PM   #19
pistalwhipped
Newbie
 
Join Date: Jan 2006
Posts: 3
Rep Power: 0 pistalwhipped is on a distinguished road
Not sure if anyone touched on this but here goes.

I had the same "requirement" for an application at my company. Basically we needed a logging system that all classes could access at the same time. So what we did is create a class "Logging" and added a static reference to it. Check it out:

public class logging 
{
	static private logging 			fInstance	= null;
	protected	string				fLogDirectory;
	protected	int					fDebugLevel;

	static public logging Instance() 
	{
		if( fInstance == null ) 
		{
			fInstance	= new logging();
		}
			return fInstance;
	}

	public	logging() 
	{
	        try 
		{
			fDebugLevel		= 1;
			fLogDirectory	= "c:/logs/";
		} 
		catch( Exception ) 
		{
			throw;
		}
	}
        public void Write( string text ) 
	{
		string fLogFileName;
		try 
		{
			DateTime	dt	= DateTime.Now;
			fLogFileName	= fLogDirectory + dt.ToString( "yyyy-MM-dd" ) + ".log";

			using( StreamWriter mLogFile = File.AppendText( fLogFileName ) ) 
			{
				mLogFile.WriteLine( text );
				mLogFile.Close();
			}

		} 
		catch( Exception ) {}
	}
}

to access the object just do the following:

logging fLog = logging.instance();

then call the Write() method. Pow! your done.
pistalwhipped is offline   Reply With Quote
Old Jan 16th, 2006, 1:57 PM   #20
Jason Isom
Programmer
 
Join Date: Dec 2005
Posts: 53
Rep Power: 3 Jason Isom is on a distinguished road
Quote:
Originally Posted by pistalwhipped
SNIP
You just used a very popular creational design pattern (maybe without realizing it?). It's called a Singleton class when you do what you're explaining, in case you wanted to research other design patterns.

I prefer to implement singletons with properties, but I guess that's just a style issue.
Jason Isom is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 7:48 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC