Laboratory - 4
Threading Concept Threading in.NET Multi-Threaded Socket Example
A thread is like a replication of a process but each replication is still belonging to a same process. Operating system concept ◦ Thread – lightweight process ◦ Process – program in memory ◦ Program – set of instruction Thread share memory but process has its own memory
Example : SimpleThread.cs Thread class 4 constructors public Thread(ThreadStart) public Thread(ParameterizedThreadStart) public Thread(ThreadStart, int) public Thread(ParameterizedThreadStart, int) Requires ThreadStart delegate for thread with no parameter Thread with parameter will require ParameterizedThreadStart
ThreadStart class SomeClass { void SomeThreadMethod() { // Some task to be performed here } void NormalMethod() { ThreadStart ts = new ThreadStart(SomeThreadMethod); Thread t = new Thread(ts); t.Start(); }
It seems that each thread runs concurrently But in practice, the context switching between threads are so fast, it appears parallelism The execution order of each thread is random In some cases, we need to have a certain task within a thread to be completed first before a context switching is carried out. For example: Race condition (RaceCondition.cs)
Many methods are available to initiate thread synchronization. In this class we will use three synchronization technique: ◦ Lock ◦ Monitor ◦ Mutex Example (Source code are given)
Previously, server can handle only one client per time We need to have a way to handle multiple client connection
In connection-oriented protocol, the RemoteEndPoint property gets the EndPoint containing the remote IP address and port number to which the Socket is connected. The RemoteEndPoint is set after a call to either Accept or Connect. It is not needed to put the whole socket program within the threading method. The part of the socket program requires to run concurrently will only be in included in multithreading method.
Multi-Threaded Server
Listener Flow
Example: EchoServerMT.cs