Threading with Synchronous Join operation
Threading to write to a file using three thread with Monitor as locking for the critical section and Thread.Join to make the entire process synchronous (though this kills the purpose of threading )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
namespace Memory_understanding
{
class writer
{
//private static Mutex mutex = new Mutex();
public void writer_method(string inputline,string thread_name)
{
Monitor.Enter(this);
using (StreamWriter str = new StreamWriter("sharedfile.txt",true))
{
str.WriteLine(inputline);
str.Close();
Console.WriteLine("Finished :" + thread_name);
Thread.Sleep(10000);
Monitor.Exit(this);
}
}
}
class ThreadWriter
{
public static void Main()
{
writer wri = new writer();
Thread t1 = new Thread(() => wri.writer_method("I will be writing from Thread1","Thread1"));
t1.Start();
//t1.Join(); // to execute the pprocess synchronously . Though it kills the purpose of threading
Thread t2 = new Thread(() => wri.writer_method("I will be writing from Thread2","Thread2"));
t2.Start();
//t2.Join(); // to execute the pprocess synchronously . Though it kills the purpose of threading
Thread t3 = new Thread(() => wri.writer_method("I will be writing from Thread3","Thread3"));
t3.Start();
//t3.Join(); // to execute the pprocess synchronously . Though it kills the purpose of threading
Console.WriteLine("Finished executing all the Threads");
Console.ReadLine();
}
}
}
Comments
Post a Comment