Threading and P/Invoke Tom Roeder CS215 2006fa. Finalization Recall C++ destructors: ~MyClass() { // cleanup } called when object is deleted does cleanup.

Slides:



Advertisements
Similar presentations
How to Build Multi- threaded Applications in.NET Mazen S. Alzogbi Technology Specialist Microsoft Corporation.
Advertisements

CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Memory Management Tom Roeder CS fa. Motivation Recall unmanaged code eg C: { double* A = malloc(sizeof(double)*M*N); for(int i = 0; i < M*N; i++)
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
C#/.NET Jacob Lewallen. C# vs.NET.NET is a platform. Many languages compile to.NET: –VB.NET –Python.NET –Managed C++ –C#
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Sharing Objects – Ch. 3 Visibility What is the source of the issue? Volatile Dekker’s algorithm Publication and Escape Thread Confinement Immutability.
University of Virginia CSharp (© John Knight 2005) 1 What’s New In C#
CPS110: Implementing threads/locks on a uni-processor Landon Cox.
1 Thread Pools. 2 What’s A Thread Pool? A programming technique which we will use. A collection of threads that are created once (e.g. when server starts).
Reflection, Conversions, and Exceptions Tom Roeder CS fa.
Peter Juszczyk CS 492/493 - ISGS. // Is this C# or Java? class TestApp { static void Main() { int counter = 0; counter++; } } The answer is C# - In C#
Platforms and tools for Web Services and Mobile Applications Introduction to C# Bent Thomsen Aalborg University 3rd and 4th of June 2004.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
11 Getting Started with C# Chapter Objectives You will be able to: 1. Say in general terms how C# differs from C. 2. Create, compile, and run a.
.NET Framework & C#.
Nachos Phase 1 Code -Hints and Comments
Overview of Threading with the.NET Framework  Wallace B. McClure  Scalable Development, Inc. Scalable Development, Inc. Building systems today that perform.
Managed C++. Objectives Overview to Visual C++.NET Concepts and architecture Developing with Managed Extensions for C++ Use cases Managed C++, Visual.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Software Engineering in Robotics Interfacing to external functions Henrik I. Christensen –
tom perkins1 XML Web Services -.NET FRAMEWORK – Part 1 CHAPTER 1.1 – 1.3.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
COMP 111 Threads and concurrency Sept 28, Tufts University Computer Science2 Who is this guy? I am not Prof. Couch Obvious? Sam Guyer New assistant.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Programming in Java CSCI-2220 Object Oriented Programming.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Upcoming Presentations ILM Professional Service – Proprietary and Confidential ( DateTimeTopicPresenter March PM Distributed.
Java Thread and Memory Model
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
Finalizers, this reference and static Sangeetha Parthasarathy 06/13/2001.
Managing C++ CHRIS DAHLBERG MID-TIER DEVELOPER SCOTTRADE.
PerlNET: The Camel Talks.NET Jan Dubois The Perl Conference 6 San Diego, July 26 th 2002.
CS533 – Spring Jeanie M. Schwenk Experiences and Processes and Monitors with Mesa What is Mesa? “Mesa is a strongly typed, block structured programming.
Object Oriented Software Development 4. C# data types, objects and references.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
OOP Basics Classes & Methods (c) IDMS/SQL News
Where Testing Fails …. Problem Areas Stack Overflow Race Conditions Deadlock Timing Reentrancy.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Object Lifetime and Pointers
C# for C++ Programmers 1.
Exceptions David Rabinowitz.
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2014
Module 9: Memory and Resource Management
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Java Programming Language
AVG 24th 2015 ADVANCED c# - part 1.
Finalization 17: Finalization
Pointers C#, pointers can only be declared to hold the memory addresses of value types int i = 5; int *p; p = &i; *p = 10; // changes the value of i to.
Multithreading.
Created By: Asst. Prof. Ashish Shah, J.M.Patel College, Goregoan West
CSE 451: Operating Systems Autumn 2003 Lecture 7 Synchronization
CSE 451: Operating Systems Autumn 2005 Lecture 7 Synchronization
CSE 451: Operating Systems Winter 2003 Lecture 7 Synchronization
Foundations and Definitions
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2018
Presentation transcript:

Threading and P/Invoke Tom Roeder CS fa

Finalization Recall C++ destructors: ~MyClass() { // cleanup } called when object is deleted does cleanup for this object Don’t do this in C# (or Java) similar construct exists but only called on GC no guarantees when

Finalization More common idiom: public void Finalize() { base.Finalize(); Dispose(false); } maybe needed for unmanaged resources slows down GC significantly Finalization in GC: when object with Finalize method created add to Finalization Queue when about to be GC’ed, add to Freachable Queue

Finalization images from MSDN Nov 2000

IDisposable and using Idea for common cleanup using(T t = new T()) { // do work with t } // t.Dispose is called by runtime IDispose provides one method: void Dispose() must provide finalizer, since must be called when called from finalizer, don’t undo managed obj often add private void Dispose(bool) using calls Dispose automatically used in class libraries, eg. for Socket

Weak References Sometimes want to keep references but not cause the GC to wait MyClass c = new MyClass(); WeakReference wr = new WeakReference(c); Now c can be collected wr will return null if referenced after c collected but to truly access the object, we get a strong ref  this is the Target property Why? Useful for large objects infrequently accessed nice to have but can be regenerated

Resurrection Imagine assigning this to global in finalizer object is now reachable again! called “resurrection” if finalizer already called, access unpredictable Should not do this but, if do, may want to reject accesses in methods what would this finalize code do: someObj = this; System.GC.ReRegisterForFinalize()

System.GC Can control the behavior of GC not recommend in general sometimes useful to give hints Some methods: Add/RemoveMemoryPressure ReRegisterFor/SuppressFinalize WaitForPendingFinalizers Collect

Memory Profiles Good lots of small short-lived objects or few but long-lived ones few links between old and new objects Bad frequently create long-lived objects create many objects that live a long but fixed amount of time

unsafe mode Sometimes need access to pointers use unsafe modifier: unsafe public void Method(out int* pi) { int i = 10; fixed(int* pj = &i) { pi = pj; } } what is wrong with this method? unsafe modifier works a method modifier or as a keyword for blocks

unsafe mode - Pointer details Can only refer to “unmanaged” types or enums or structs composed of unmanaged types Not a subclass of object void* exists, but no arithmetic allowed boxing/unboxing does not work stackalloc gets memory from the stack

unsafe mode Cannot be executed in untrusted context security requirement: so can’t change memory eg. avoid stack smashing attacks pointer types cannot refer to a reference cannot refer to a struct that contains references int* pi, pj;// NOT int *pi, *pj;

Threading Threading provides concurrent execution Even useful on multiprocessor As opposed to “sequential” execution Comes at cost of overhead Can be dangerous For example public int Increment(ref int x) { return ++x; } What happens when called by two threads? How to fix?

Threading How to create a Thread Create a new Thread instance with delegate Type: public delegate void ThreadStart(); Call Start method Let’s do an example on the board Thread will be scheduled when possible on SMP, may actually have many threads at once on UP, still may be useful when blocked as in UI, networking code, dealing with drivers

Threading Need synchronization primitives Way to ensure that only one thread executes code in a region at once Called “critical section” C# provides (mostly in System.Threading) lock statement Monitor class Interrupt several others (see Birrell’s paper or MSDN)

Threading model: lock Basic idea: each object has a lock public int Increment(ref int x) {lock(this) return ++x;} lock prevents more than one thread from entering forces sequential order What should we lock on? for instance variables: this for globals and statics: typeof(container) something that will be same for all threads that access this shared memory

Threading model: Monitor Monitors provide synchronization construct entry waits on a queue waiting lets a new thread enter Monitor.Enter and Monitor.Exit same semantics as the lock construct Why do we need both? Gets a lock on the object Cannot be used on value types: why not?

Threading model: Monitor Methods Monitor.Enter/Monitor.Exit enter/exit the monitor for a given object Monitor.Wait wait on a given object must be inside a monitor for that object signal-delayed semantics Monitor.Pulse/Monitor.PulseAll some thread(s) can be released to try the monitor

Threading model: Interrupt Sometimes need to wake up a thread eg. if UI cancelled eg. if event no longer needed Standard OO way: exceptions Interrupt causes thread to throw ThreadInterruptedException only on Wait or Sleep Allows cleanup of invariants

Other synchro classes Abort throws exception immediately difficult to clean up: Why? usually too draconian Mutex and other synchronization good for interacting with Windows but stick with lock and Monitor, normally ReaderWriter Locks not clear exactly what semantics they implement

Threading model: ThreadPool Instead of explicitly creating threads create a pool pass delegates to worker threads enqueued in pool QueueUserWorkItem takes a WaitCallback delegate Good for large amounts of parallel work eg. N-Body problem automatically scales to number of processors “embarrasingly parallel” problems

Threading Conclusions Standard monitor semantics as in Java useful constructions OS synchronization exposed native ThreadPool Really only need lock Monitor

P/Invoke Use special attributes to make system calls eg. [DllImport(“kernel32”)] static extern int GetProcessHeap(); calls to function in C library problems for C++ name mangling: doesn’t match General problem of COM/.NET interop why does this matter?

COM Interoperability Need metadata generated from TypeLib Can then use COM class like.NET class even though major differences in models eg. threading, registration, inheritance useful for backwards compatibility Can bind early or late to class either we know its type at compile time or not

Calling a COM Server namespace CallingCOMServer { using System; using COMServerLib; public class DotNET_COMClient {... public static int Main(string[] args) { MyCOMServer myS = new MyCOMServer(); return (myS.Add (17,4)); } };

Late-Bound Activation Use Reflection to get the type of the class ProgID / ClassID: looked up in registry gives type of COM object Can instantiate instance and call methods uses InvokeMethod to call methods don’t have as strong type information here COM object wrapped by __ComObject can sometimes use as to get better info

Late-Bound namespace LateBoundClient { using System.Reflection;... Type typ; Object obj; Object[] prms = new Object[2]; int r; typ = Type.GetTypeFromProgID(„MyLib.MyServer"); obj = Activator.CreateInstance(typ); prms[0] = 10; prms[1] = 150; r = (int)typ.InvokeMember(„aMethod", BindingFlags.InvokeMethod, null, obj, prms);... }

.NET from COM Needs to be public with public methods Need to register a wrapper: use RegAsm tool provides ProgID/ClassID information for registry necessary for COM integration Metadata must be converted to TypeLibrary Have same early- and late-bound activation early: by name late: by ProgID/ClassID

Platform from.NET Calling static functions in DLLs P/Invoke provides services Locates implementing DLL Loads DLL Finds function address Fuzzy name matching algorithm Pushes arguments on stack Performs marshalling Enables pre-emptive garbage collection Transfers control to unmanaged code

P/Invoke Example namespace HelloWorld { using System; class MyClass { [dllimport(“user32.dll”, CharSet=CharSet.Ansi)] static extern int MessageBox(int h, string m, string c, int t); public static int Main() { return MessageBox(0, "Hello World!", "Caption", 0); } } }

P/Invoke Callbacks Unmanaged code can call back to managed code Unmanaged parameter is function pointer Must supply parameter as delegate P/Invoke creates callback thunk Passes address of thunk as callback parameter Managed Code.NET Application Call passes pointer to callback function Implementation of callback function Unmanaged Code DLL DLL function

Callback Example public class EnumReport { public bool Report(int hwnd, int lParam) { // report the window handle Console.Write("Window handle is "); Console.WriteLine(hwnd); return true; } }; public class SampleClass { delegate bool CallBack(int hwnd, int lParam); [DllImport("user32")] static extern int EnumWindows(CallBack x, int y); public static void Main() { EnumReport er = new EnumReport(); CallBack myCallBack = new CallBack(er.Report); EnumWindows(myCallBack, 0); } }

Managed Extensions for C++ Allows C++ code to be managed by GC/CLR compile with /clr: It Just Works generates MSIL from C++ contains, eg __gc, __box, __typeof, __interface, __property #pragma managed/unmanaged Very useful for native access to C++ libraries build a “managed wrapper” Partial conversion to managed code