cs480_110211

download cs480_110211

of 27

Transcript of cs480_110211

  • 8/3/2019 cs480_110211

    1/27

    cs480 (Prasad) L11Threads 1

    Cooperative Concurrent Threads

    Producer-Consumer Problem

    Bounded-Buffer Problem

    (Clients and Servers : Resource Sharing)

  • 8/3/2019 cs480_110211

    2/27

    cs480 (Prasad) L11Threads 2

    Simplistic 1-Cell Buffer

    class Buffer {Object x;

    // synchronized

    public void put (Object _x, String id) {

    System.out.println(

    "Done > " + id + " gets " + x);return x;

    }

    }

  • 8/3/2019 cs480_110211

    3/27

    cs480 (Prasad) L11Threads 3

    class Producer extends Thread {

    private Random r = new Random();

    Buffer b; String id;public Producer(Buffer _b, String _id) {

    b = _b; id = _id;

    }

    public void run () {

    int delay; Integer ir;

    try {

    while (true) {

    delay = Math.abs(r.nextInt() % 1999) + 50;

    sleep(delay); ir = new Integer(delay);

    System.out.println("Ready

  • 8/3/2019 cs480_110211

    4/27

    cs480 (Prasad) L11Threads 4

    class Consumer extends Thread {

    private Random r = new Random();

    Buffer b; String id;

    public Consumer(Buffer _b, String _id) {

    b = _b; id = _id;

    }

    public void run () {

    int delay; Integer ir = null;

    try

    {while (true) {

    delay = Math.abs(r.nextInt() % 1999) + 50;

    sleep(delay);

    System.out.println("Ready >> " + id + " gets ");

    ir = (Integer) b.get(id);

    }} catch (Exception e) {System.out.println("Exception$ " + e);};

    }

    }

  • 8/3/2019 cs480_110211

    5/27

    cs480 (Prasad) L11Threads 5

    Producer-Consumer : Bounded Bufferpublic class PCB {public static void main(String[] args) {

    Buffer b = new Buffer();

    new Consumer(b,"C1") . start();

    new Producer(b,"P1") . start();

    try {Thread.sleep(1000);

    } catch (Exception e){};

    new Consumer(b,"C2") . start();

    new Producer(b,"P2") . start();

    }

    }

  • 8/3/2019 cs480_110211

    6/27

    cs480 (Prasad) L11Threads 6

    Unfettered Run

    Ready >> C1 gets

    Ready > C1 gets null

    Done > C1 gets

    Done >> C1 gets 488

    Ready >> C2 getsDone >> C2 gets 488

    Ready C2 gets 815Ready C1 gets

    Done >> C1 gets 1223

    Ready C2 gets

    Done >> C2 gets 403

    ...

    (transient stability?!)premature

    puts

    gets

  • 8/3/2019 cs480_110211

    7/27

    cs480 (Prasad) L11Threads 7

    Concurrency control : class Bufferclass Buffer {

    Object x;boolean empty = true;public synchronized void put

    (Object _x, String id) throws Exception{ ...}

    public synchronized Object get

    (String id) throws Exception { ... }}

    Two producers (consumers) cannot put(get) twoitems in (from) the same buffer slotsimultaneously.

    Two producers (consumers) cannot put(get) twoitems in (from) the same buffer slot without anintervening consumer (producer).

    A consumer (producer) is not permitted to get(put)an item from (into) buffer if empty (full).

  • 8/3/2019 cs480_110211

    8/27

    cs480 (Prasad) L11Threads 8

    public synchronized void

    put (Object _x, String id) throws Exception {

    while (!empty) wait();

    empty = ! empty;

    System.out.println("Done

  • 8/3/2019 cs480_110211

    9/27

    cs480 (Prasad) L11Threads 9

    public synchronized Object

    get (String id) throws Exception {while (empty) wait();

    empty = ! empty;

    System.out.println("Done >> "+id+" gets "+x);

    notifyAll();return x;

    }

    Note that notify cannot always be used inplace ofnotifyAll because a consumer may be woken up.

    while required because notifyAlldue to a producerdoes not guarantee that wait-ing consumers will find anitem in the buffer.

  • 8/3/2019 cs480_110211

    10/27

    cs480 (Prasad) L11Threads 10

    Synchonization and Mutual Exclusion

    Ready >> C2 gets

    Ready >> C1 gets

    Ready C2 gets 1672

    Ready C1 gets 774

    Ready C1 gets

    Done >> C1 gets 168

    Ready C1 gets

    Done >> C1 gets 1263

    ...

    Ready C1 gets

    Done >> C1 gets 622

    Ready >> C2 gets

    Ready C2 gets 1447

    Ready > C1 gets 96

    Done

  • 8/3/2019 cs480_110211

    11/27

    cs480 (Prasad) L11Threads 11

    Methods in class Object

    public final void wait() throwsInterruptedException {...}

    Current thread is suspended (afteratomicallyreleasing the lock on this) until some other thread

    invokes notify()ornotifyAll()orinterrupts.

    public final void notify() {...}Notifies exactly one thread waiting on thisobject for

    a condition to change. The awakened thread cannot

    proceed until this thread relinquishes the lock.

    public final void notifyAll() {...} These methods must be invoked inside synchronized

    code or else IllegalMonitorStateExceptionwill be thrown.

  • 8/3/2019 cs480_110211

    12/27

    cs480 (Prasad) L11Threads 12

    Single Cell Buffer in C#

    using System;

    using System.Threading;

    class Buffer {

    Object x;

    bool empty = true;

    public void put (Object _x, string id) {

    lock(this){

    while (!empty) Monitor.Wait(this);

    empty = ! empty;

    Console.WriteLine("Done > " + id + " gets " + x);

    Monitor.PulseAll(this);

    return x;

    }

    }

    }

  • 8/3/2019 cs480_110211

    13/27

    cs480 (Prasad) L11Threads 13

    class Producer {

    private System.Random r = new System.Random();

    Buffer b; String id;

    public Producer(Buffer _b, String _id) {

    b = _b; id = _id;

    }

    public void run () {

    int delay;

    try {

    while (true) {

    delay = r.Next(2000) + 50;

    Thread.Sleep(delay);

    Console.WriteLine("Ready

  • 8/3/2019 cs480_110211

    14/27

    cs480 (Prasad) L11Threads 14

    class Consumer {

    private System.Random r = new System.Random();

    Buffer b; String id;

    public Consumer(Buffer _b, String _id) {

    b = _b; id = _id;

    }

    public void run () {

    int delay;

    try {

    while (true) {

    delay = r.Next(2000) + 50;

    Thread.Sleep(delay);

    Console.WriteLine("Ready >> " + id + " gets ");

    delay = (int) b.get(id);

    }

    } catch (Exception e)

    {Console.WriteLine("Exception$ " + e);};

    }

    }

  • 8/3/2019 cs480_110211

    15/27

    cs480 (Prasad) L11Threads 15

    public class PCB {

    public static void Main(string[] args) {

    Buffer b = new Buffer();

    new Thread( new ThreadStart(new Consumer(b,"C1").run)) . Start();

    new Thread( new ThreadStart(new Producer(b,"P1").run)) . Start();

    try {Thread.Sleep(1000);}

    catch (Exception e){Console.WriteLine("Exception$ " + e);};

    new Thread( new ThreadStart(new Consumer(b,"C2").run)) . Start();

    new Thread( new ThreadStart(new Producer(b,"P2").run)) . Start();

    }

    }

  • 8/3/2019 cs480_110211

    16/27

    cs480 (Prasad) LSysVsScipt 16

    Scripting vs Systems Programming

    Languages

    Designed for gluingapplications : flexibility

    Interpreted Dynamic variable creation Data and code integrated :

    meta-programmingsupported

    Dynamic typing (typeless) Examples: PERL, Tcl,

    Python, Ruby, Scheme,Visual Basic, etc

    Designed for buildingapplications : efficiency

    Compiled Variable declaration Data and code separated :

    cannot create/run code onthe fly

    Static typing Examples: PL/1, Ada,

    Java, C/C++, C#, etc

  • 8/3/2019 cs480_110211

    17/27

    cs480 (Prasad) LSysVsScipt 17

    (contd)

    Does application implement complex algorithms and datastructures?

    Does application process large data sets (>10,000 items)? Are application functions well-defined, fixed?If yes, consider a system programming language.

    Is the main task to connect components, legacy apps? Does the application manipulate a variety of things? Does the application have a GUI? Are the application's functions evolving rapidly? Must the application be extensible? Does the application do a lot of string manipulation?If yes, consider a scripting language.

  • 8/3/2019 cs480_110211

    18/27

    cs480 (Prasad) LSysVsScipt 18

    Current Trends

    Hybrid Languages : Scripting + Systems Programming Recent JVM-based Scripting Languages

    Jython : Python dialectClojure : LISP dialectScala : OOP +Functional Hybrid

  • 8/3/2019 cs480_110211

    19/27

    cs480 (Prasad) LSysVsScipt 19

    Jython (for convenient access to Java APIs)

    I:\tkprasad\cs480>jython

    Jython 2.1 on java1.4.1_02 (JIT: null)

    Type "copyright", "credits" or "license" for more information.

    >>> import javax.swing as swing

    >>> win = swing.JFrame("Welcome to Jython")

    >>> win.size = (200, 200)

    >>> win.show()>>> ^Z

  • 8/3/2019 cs480_110211

    20/27

    cs480 (Prasad) LSysVsScipt 20

    Java vs Jython

    map = new HashMap();map.put("one",new Integer(1));map.put("two",new Integer(2));map.put("three",new Integer(3));

    System.out.println(map.get("one"));

    list = new LinkedList();

    list.add(new Integer(1));list.add(new Integer(2));list.add(new Integer(3));

    map = {"one":1,"two":2,"three":3}

    print map ["one"]

    list = [1, 2, 3]

  • 8/3/2019 cs480_110211

    21/27

    cs480 (Prasad) LSysVsScipt 21

    (contd)

    for i in list:

    (* iterator *)

    newList =[function(i) for i in oldList]

    (* list comprehension *)

    for (Iterator i; i.hasNext();){

    i.next();

    }

    List newList = ArrayList()for (Iterator i; i.hasNext();){

    Object obj = i.next();newList.add(function(obj))

    }

  • 8/3/2019 cs480_110211

    22/27

    cs480 (Prasad) LSysVsScipt 22

    Defining functions and expressions in Jython

    (file: eg.py)

    list =[pow(i,i) for i in [1,2]]

    from math import *print PI=%f, e=%f % (pi,e)

    Y = range(1,9,1)# [1,2,3,4,5,6,7,8]Y[1:3]#[2, 3]Y[::2]

    #[1, 3, 5, 7]

    def fac(x) :factorial functionif x

  • 8/3/2019 cs480_110211

    23/27

    cs480 (Prasad) LSysVsScipt 23

    More Jython code examples

    Dynamic code evaluationprint eval ([1,3] + range(6,10,3))

    # [1, ,3, 6, 9]

    x = 2 + 3j

    exec x = 5, x + x

    #(5, (4+6j)

  • 8/3/2019 cs480_110211

    24/27

    cs480 (Prasad) LSysVsScipt 24

    Contd

    Exceptionsdef readfile (name):return lines in file or None if unreadable

    try: file = open(name, r)try: # raise IOError

    return file.readlines()finally:

    file.close()except IOError, ioe:

    print Exception , ioe

  • 8/3/2019 cs480_110211

    25/27

    cs480 (Prasad) LSysVsScipt 25

    Contd

    Functional Programmingapply(lambda x,y : x*y, (10, 20))

    # 200

    map(lambda x,y: x + y, [[1,2],[a]], [[3],[b]])# [[1, 2, 3], [a, b]]

    reduce(lambda x,y: x + y, [1,2,3], 100)

    # 106

    filter(lambda x: x > 0, range(10,-5,-3))# [10, 7 , 4, 1]

  • 8/3/2019 cs480_110211

    26/27

    cs480 (Prasad) LSysVsScipt 26

    import java.lang as langimport javax.swing as swingimport java.awt as awt

    names = ["Groucho", "Chico", "Harpo"]

    quotes = {"Groucho": "Say the secret word", "Chico": "Viaduct?","Harpo": "HONK!"}

    def buttonPressed(event):field.text = quotes[event.source.text]

    def exit(event):lang.System.exit(0)

    def createButton(name):return swing.JButton(name, preferredSize=(100,20),actionPerformed=buttonPressed)

    Java functionality through Jython

  • 8/3/2019 cs480_110211

    27/27

    cs480 (Prasad) LSysVsScipt 27

    win = swing.JFrame("Welcome to Jython", size=(200,200),windowClosing=exit)

    win.contentPane.layout = awt.FlowLayout( )

    field = swing.JTextField(preferredSize=(200,20))win.contentPane.add(field)

    buttons = [createButton(each) for each in names]

    for eachButton in buttons:win.contentPane.add(eachButton)

    win.pack( )win.show( )