Threads & Networking

Similar documents
Exercise Session Week 8

Exercise Session Week 8

Advanced Programming C# Lecture 13. dr inż. Małgorzata Janik

Advanced Programming C# Lecture 12. dr inż. Małgorzata Janik

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Java Threads. Introduction to Java Threads

CMSC 132: Object-Oriented Programming II. Threads in Java

7. MULTITHREDED PROGRAMMING

Introduction to Java Threads

Multiple processes can run in parallel on a single computer and multiple threads can run in parallel in a single process.

Systems Programming & Scripting

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

Threads Chate Patanothai

The Network. Multithreading. This tutorial can be found on -

Threads are lightweight processes responsible for multitasking within a single application.

Processes and Threads. Industrial Programming. Processes and Threads (cont'd) Processes and Threads (cont'd)

Java Threads. COMP 585 Noteset #2 1

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

CMSC 132: Object-Oriented Programming II

Process Characteristics. Threads Chapter 4. Process Characteristics. Multithreading vs. Single threading

Threads Chapter 4. Reading: 4.1,4.4, 4.5

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

COMP346 Winter Tutorial 4 Synchronization Semaphores

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

Multithreaded Programming

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

M.C.A. (CRCS) (Sem.-IV) Examination May-2014 Paper: CCA Net Framework and C# Faculty Code: 003 Subject Code:

Lecture 35. Threads. Reading for next time: Big Java What is a Thread?

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Multi-threading in Java. Jeff HUANG

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

CS 351 Design of Large Programs Threads and Concurrency

Java Threads and intrinsic locks

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

User Space Multithreading. Computer Science, University of Warwick

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Programming in Parallel COMP755

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

CS193k, Stanford Handout #8. Threads 3

Parallel Programming Languages COMP360

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Threads and Parallelism in Java

Multiple Inheritance. Computer object can be viewed as

Deadlock. Only one process can use the resource at a time but once it s done it can give it back for use by another process.

CS 556 Distributed Systems

BSc ( Hons) Computer Science with Network Security. Examinations for / Semester 2

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Outline of lecture. i219 Software Design Methodology 10. Multithreaded programming. Kazuhiro Ogata (JAIST)

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

Internet Technology 2/7/2013

Java Threads. Written by John Bell for CS 342, Spring 2018

Multithreading and Interactive Programs

Tommy Färnqvist, IDA, Linköping University

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Reintroduction to Concurrency

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Concurrent Programming using Threads

System Programming. Practical Session 4: Threads and Concurrency / Safety

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Java s Implementation of Concurrency, and how to use it in our applications.

Networking: IPv6, UDP and TCP. Network Programming in Java UDP and TCP

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Lecture 21: Concurrency in Other Environments (Part 2)

Performance Throughput Utilization of system resources

CS11 Java. Fall Lecture 7

CSCD 330 Network Programming

Virtual Machine Design

Part IV Other Systems: I Java Threads

CSE 451 Midterm 1. Name:

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Threads and Java Memory Model

Program #3 - Airport Simulation

DAD Lab. 2 Additional C# Topics

Unit - IV Multi-Threading

SOCKETLIB. Requirements

Self-test Java Programming

CSC Java Programming, Fall Java Data Types and Control Constructs

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

Module - 4 Multi-Threaded Programming

CS 160: Interactive Programming

CSCD 330 Network Programming

Question Points Score Total 100

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2012

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015

CSCD 330 Network Programming

CMSC 330: Organization of Programming Languages

C# Syllabus. MS.NET Framework Introduction

Threads in Java. Threads (part 2) 1/18

COP 4610: Introduction to Operating Systems (Spring 2015) Chapter 4: Threads. Zhi Wang Florida State University

University of Palestine. Mid Exam Total Grade: 100

Software Practice 3 Today s lecture Today s Task

Synchronization in Java

Transcription:

Threads & Networking C# offers facilities for multi threading and network programming an application roughly corresponds to a process, handled by the OS time sharing simulates multi tasking inside an application : several execution threads

Multitasking P1 P2 P3 T3_1 T3_2 time P1 P2 P 3 T 3 1 T 3 2 P1 P2 P 3 T 3 1 T 3 2

Multithreading thread = 'light' process several threads belonging to a single application share the same memory space : efficient communication the main process is a thread : the main thread easy creation of a thread associated to a method : the method is ran independantly of the program

Multithreading the method is run 'out of sequence' (asynchronously) and sometimes needs synchronization with other threads. Thread class implements _Thread interface public sealed class Thread : _Thread

Creating a thread : example class test static void run() // some interesting code inside static void Main(string[] args) Thread th0 = new Thread(new ThreadStart(run run)); th0.start();

class thapp public static void countup() long i; for (i=1; i <=100;i++) System.Console.WriteLine(i.ToString()); class test static void Main(string[] args) Thread th0 = new Thread(new ThreadStart(thApp.countup thapp.countup)); th0.start();

class thapp2 public void hello() System.Console.WriteLine("hello world!"); class test static void Main(string[] args) thapp2 myvar = new thapp2(); Thread th0 = new Thread(new ThreadStart(mavar.hello mavar.hello)); th0.start();

Parameterized Thread Foo parameter = // get parameter value Thread thread = new Thread(new ParameterizedThreadStart(DoMethod)); thread.start(parameter); // overloaded method // signature of function should not be changed! (part of a delegate) private void DoMethod(object obj) Foo parameter = (Foo)obj; //...

Parmeterized Thread The best way to do it is to use your own class that contains state Type safe compared to the previous example that passes an object This could raise an exception if the object is not an instance of the correct type!

Parameterized Thread public class ThreadWithState // State information used in the task. private string boilerplate; private int value; // The constructor obtains the state information. public ThreadWithState(string text, int number) boilerplate = text; value = number; // The thread procedure performs the task, such as formatting // and printing a document. public void ThreadProc() Console.WriteLine(boilerplate, value);

Parameterized Thread public static void Main() // Supply the state information required by the task. ThreadWithState tws = new ThreadWithState( "This report displays the number 0.", 42); // Create a thread to execute the task, and then // start the thread. Thread t = new Thread(new ThreadStart(tws.ThreadProc)); t.start(); Console.WriteLine("Main thread does some work, then waits."); t.join(); Console.WriteLine( "Independent task has completed; main thread ends.");

Destroying a Thread Use «Abort» function Stops the thread and the CLR raises throws a ThreadAbortException in the target thread The Abort method does not cause the thread to abort immediately the target thread can catch the ThreadAbortException and execute arbitrary amounts of code in a finally block

Synchronization class test static void Main(string[] args) Thread th0 = new Thread(new threadstart(thapp.countup)); th0.start(); thapp2 myvar = new thapp2(); th0 = new Thread(new ThreadStart(myvar.hello)); th0.start(); // don't forget the pause

Synchronization executing the program 3 times gives the following result : 1 2 3 22 hello world! 23 24 99 100 1 2 3 4 hello world! 5 6 7 99 100 1 2 3 22 23 24 99 100 hello world!

Synchronization to ensure synchronization, use : sleep() abort() join() interrupt()

locks & semaphores several threads sharing a resource critical section : exclusive execution use a lock to ensure exclusivity

locks & semaphores in each thread willing to access an exclusive resource : object access_grant=new object(); lock(access_grant) critical section;

locks & semaphores problem : access_grant is local to each thread : use a static object to share among threads class mythread static object access_grant = new object(); public void mymethod() lock(access_grant) critical section;

locks & semaphores class test static void Main(string [] args) mythread [] progs = new mythread[3]; foreach (mythread m in progs) new Thread(new ThreadStart(m.myMethod)).Start();

locks & semaphores if a thread asks for access while already locked : thread is queued wrt the access_grant object. use the Monitor class to check access_grant status before entering critical section

Monitor class object access_grant = new object(); Monitor.Enter(access_grant); critical section; Monitor.Exit(access_grant); TryEnter method : if the resource is locked, do something else.

Monitor class if (Monitor.TryEnter(access_grant)) // true if resource is available else critical section code do something interesting anyway

Semaphore and Mutex to synchronize threads and processus :use the Semaphore and Mutex classes static Semaphore sem(0,n); // initial and max threads allowe to possess the semaphore sem.waitone() critical section sem.release()

Semaphore and Mutex a Mutex is a Semaphore with initial count=0 ans a max count = 1 for more informations on semaphores, locks, monitors, see your OS documentation.

Working with processes a little break in theory how to list processes on the local computer use the System.Diagnostics classes and the Process class

Working with processes class test static void Main(string [] args) Process [] locals = Process.GetProcesses(); foreach(process p in locals) System.Console.Write(p.ProcessName); // pause

Working with processes class test static void Main(string [] args) Process appex = new Process(); appex.startinfo.filename = "path_to_exe"; appex.startinfo.useshellexecute = false; appex.startinfo.redirectstandardoutput = false; appex.start(); // target application starts here // pause Executing a standard application (any.exe) from a C# program

Networking made easy use System.Net and System.Net.Sockets C# : TcpListener and TcpClient classes server client 1 listen to connections trough a TcpListener 2 connection to server through a TcpClient 3 connection is accepted : dialog through a TcpClient 4 dialog through TcpClients

Sample server code class server private TcpListener ear; private TcpClient cli_sock; public server() byte [] local_ip =127,0,0,1; ear = new TcpListener(new IPAdress(local_IP),8080); ear.start(); cli_sock = ear.accepttcpclient(); // blocking // now talk with the client

Sample client code class client private TcpClient sock; public client() sock = new TcpClient("server_name",8080); // now talk with the server if connected

Multi client server Server TcpListener Connexion acceptance connexion Client TcpClient TcpClient Thread

working with streams input and output streams to read/write with TcpClient objects StreamReader in=new StreamReader(sock.GetStream()); StreamWriter out=new StreamWriter(sock.getStream()); out.autoflush=true; read data with in.readline(); write data with out.writeline();

networks and threads sockets (TcpClient objects) may send and receive information at any time : use a thread to run a method that receives information : while (connection is valid) read data sent by the server-side socket;

network applications : Communication using sockets and a communication protocol dedicated to the application; existing protocol : SMTP, FTP, HTTP, SOAP : Web development.