2.3 InterProcess Communication (IPC) - PowerPoint PPT Presentation

Loading...

PPT – 2.3 InterProcess Communication (IPC) PowerPoint presentation | free to download - id: 7327ab-NDVhY



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

2.3 InterProcess Communication (IPC)

Description:

2.3 InterProcess Communication (IPC) Part C – PowerPoint PPT presentation

Number of Views:1
Avg rating:3.0/5.0
Date added: 3 September 2018
Slides: 65
Provided by: George753
Learn more at: http://people.sju.edu
Category:

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: 2.3 InterProcess Communication (IPC)


1
2.3 InterProcess Communication (IPC)
  • Part C

2
IPC methods
  1. Signals
  2. Mutex (MUTual EXclusion)
  3. Semaphores
  4. Shared memory
  5. Memory mapped files
  6. Pipes named pipes
  7. Sockets
  8. Message queues
  9. MPI (Message Passing Interface)
  10. Barriers

3
Pipes and named pipes
4
Pipes
Cmd1s stdout becomes Cmd2s stdin.
one direction only
5
More Pipes
6
Too many pipes?!
7
Pipes via pipe()(child writing to parent)
  • // Excerpt from "Linux Programmer's Guide -
    Chapter 6."
  • // (C)opyright 1994-1995, Scott Burkett
  • include ltstdio.hgt
  • include ltunistd.hgt
  • include ltsys/types.hgt
  • int main ( int argc, char argv )
  • int fd2, nbytes
  • pid_t childpid
  • char string "Hello, world!\n",
    readbuffer80
  • pipe( fd ) //fd0 is opened for reading
    (input side)
  • // fd1 is opened for writing (output side).

8
Pipes via pipe()(child writing to parent)
  • // Excerpt from "Linux Programmer's Guide -
    Chapter 6."
  • // (C)opyright 1994-1995, Scott Burkett
  • include ltstdio.hgt
  • include ltunistd.hgt
  • include ltsys/types.hgt
  • int main ( int argc, char argv )
  • int fd2, nbytes
  • pid_t childpid
  • char string "Hello, world!\n",
    readbuffer80
  • pipe( fd ) //fd0 is opened for reading
    (input side)
  • // fd1 is opened for writing (output side).
  • if ( (childpid fork()) -1 )
  • perror( "fork" )
  • exit( 1 )

9
Pipes via pipe()(child writing to parent)
  • // Excerpt from "Linux Programmer's Guide -
    Chapter 6."
  • // (C)opyright 1994-1995, Scott Burkett
  • include ltstdio.hgt
  • include ltunistd.hgt
  • include ltsys/types.hgt
  • int main ( int argc, char argv )
  • int fd2, nbytes
  • pid_t childpid
  • char string "Hello, world!\n",
    readbuffer80
  • pipe( fd ) //fd0 is opened for reading
    (input side)
  • // fd1 is opened for writing (output side).
  • if ((childpid fork()) -1)
  • perror( "fork" )
  • exit( 1 )
  • if (childpid 0) //child process
    closes input side of pipe, writes
  • close( fd0 )
  • / Send "string" through the
    output side of pipe /

10
Pipes via pipe()(child writing to parent)
  • // Excerpt from "Linux Programmer's Guide -
    Chapter 6."
  • // (C)opyright 1994-1995, Scott Burkett
  • include ltstdio.hgt
  • include ltunistd.hgt
  • include ltsys/types.hgt
  • int main ( int argc, char argv )
  • int fd2, nbytes
  • pid_t childpid
  • char string "Hello, world!\n",
    readbuffer80
  • pipe( fd ) //fd0 is opened for reading
    (input side)
  • // fd1 is opened for writing (output side).
  • if ((childpid fork()) -1)
  • perror( "fork" )
  • exit( 1 )
  • if (childpid 0) //child process
    closes input side of pipe, writes
  • close( fd0 )
  • / Send "string" through the
    output side of pipe /

This is child writing to parent. How can we
change it to be parent to child?
11
Pipes via pipe()(parent writing to child)
  • // Excerpt from "Linux Programmer's Guide -
    Chapter 6."
  • // (C)opyright 1994-1995, Scott Burkett
  • include ltstdio.hgt
  • include ltunistd.hgt
  • include ltsys/types.hgt
  • int main ( int argc, char argv )
  • int fd2, nbytes
  • pid_t childpid
  • char string "Hello, world!\n",
    readbuffer80
  • pipe( fd ) //fd0 is opened for reading
    (input side)
  • // fd1 is opened for writing (output side).
  • if ((childpid fork()) -1)
  • perror( "fork" )
  • exit( 1 )
  • if (childpid ! 0) //parent process
    closes input side of pipe, writes
  • close( fd0 )
  • / Send "string" through the
    output side of pipe /

That was easy!
12
Pipes between processes (using popen)
13
Problem
  • I need to sort data but its complicated so I
    cant use the regular sort function.
  • There is a program called sort that can do it for
    me.
  • But how can I use it?

14
Pipes via popen()(pipes to/from processes)
  • // Excerpt from "Linux Programmer's Guide -
    Chapter 6."
  • // (C)opyright 1994-1995, Scott Burkett
  • include ltstdio.hgt
  • define MAXSTRS 5
  • int main ( int argc, char argv )
  • FILE pipe_fp
  • char strings MAXSTRS "echo",
    "bravo", "alpha", "charlie", "delta"
  • / Create one way pipeline with call to
    popen() /
  • if (( pipe_fp popen("sort", "w"))
    NULL)
  • perror( "popen" )
  • exit( 1 )
  • / Processing loop /
  • for (int cntr0 cntrltMAXSTRS cntr)
  • fputs( stringscntr, pipe_fp )
  • fputc( '\n', pipe_fp )
  • / Close the pipe /

Can be w or r.
Any valid shell command.
15
Pipes via popen()(pipes to/from processes)
  • // Excerpt from "Linux Programmer's Guide -
    Chapter 6."
  • // (C)opyright 1994-1995, Scott Burkett
  • include ltstdio.hgt
  • define MAXSTRS 5
  • int main ( int argc, char argv )
  • FILE pipe_fp
  • char strings MAXSTRS "echo",
    "bravo", "alpha", "charlie", "delta"
  • / Create one way pipeline with call to
    popen() /
  • if (( pipe_fp popen("sort", "w"))
    NULL)
  • perror( "popen" )
  • exit( 1 )
  • / Processing loop /
  • for (int cntr0 cntrltMAXSTRS cntr)
  • fputs( stringscntr, pipe_fp )
  • fputc( '\n', pipe_fp )
  • / Close the pipe /

16
Pipes via popen()
  • // Excerpt from "Linux Programmer's Guide -
    Chapter 6"
  • // (C)opyright 1994-1995, Scott Burkett
  • include ltstdio.hgt
  • define MAXSTRS 5
  • int main ( int argc, char argv )
  • FILE pipe_fp
  • char strings MAXSTRS "echo",
    "bravo", "alpha", "charlie", "delta"
  • / Create one way pipeline with call to
    popen() /
  • if (( pipe_fp popen("sort", "w"))
    NULL)
  • perror( "popen" )
  • exit( 1 )
  • / Processing loop /
  • for (int cntr0 cntrltMAXSTRS cntr)
  • fputs( stringscntr, pipe_fp )
  • fputc( '\n', pipe_fp )
  • / Close the pipe /

How would I modify this to obtain the sorted
information?
17
Pipes via popen()
  • // Excerpt from "Linux Programmer's Guide -
    Chapter 6"
  • // (C)opyright 1994-1995, Scott Burkett
  • include ltstdio.hgt
  • define MAXSTRS 5
  • int main ( int argc, char argv )
  • FILE pipe_fp
  • char strings MAXSTRS "echo",
    "bravo", "alpha", "charlie", "delta"
  • / Create one way pipeline with call to
    popen() /
  • if (( pipe_fp popen("sort gt junk.dat",
    "w")) NULL)
  • perror( "popen" )
  • exit( 1 )
  • / Processing loop /
  • for (int cntr0 cntrltMAXSTRS cntr)
  • fputs( stringscntr, pipe_fp )
  • fputc( '\n', pipe_fp )
  • / Close the pipe /

Any valid shell command.
How would I modify this to have obtain the sorted
information? This works, but is junk.dat unique?
18
Named pipes
19
Named pipes
  • Named pipes
  • Use mkfifo command. (What is a FIFO?)
  • Example
  • mkfifo mypipe
  • ls l mypipe
  • prw------- 1 ggrevera ggrevera 0 Oct 5 2130
    mypipe
  • ls l gt mypipe
  • Hangs! Why?
  • Ctrl-c
  • ls l gt mypipe
  • cat lt mypipe
  • Doesnt hang! Why?

20
Using a pipe to communicate to a childs stdin
  • include ltassert.hgt
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • include ltstrings.hgt
  • include ltsys/types.hgt
  • include ltunistd.hgt
  • int main ( int argc, char argv )
  • int fd 2
  • pipe( fd ) //fd0 is opened for reading
    (input side)
  • // fd1 is opened for writing (output side).
  • pid_t childpid fork()
  • assert( childpid ! -1 )
  • if (childpid 0) //in child process
  • close( fd1 ) //MUST close unused side
    of pipe
  • close( 0 ) //close child's
    current, default stdin
  • dup( fd0 ) //duplicate input side
    of pipe to stdin
  • execlp( "sort", "sort", "-n", NULL )
  • perror( "exec failed." ) //should never
    get here!
  • exit( -1 )
  • else //in parent process
  • close( fd0 ) //close unused side of
    pipe
  • //write info to pipe
  • char buff 256
  • for (int i0 ilt10 i)
  • sprintf( buff, "d \n", i )
  • write( fd1, buff, strlen(buff) )
  • close( fd1 ) //indicates that we
    are done
  • int status
  • wait( status ) //wait for child to
    finish

parents fd1 ----gt childs stdin
21
Named pipes
  • Named pipes
  • Use mkfifo command. (What is a FIFO?)
  • Example
  • mkfifo mypipe
  • ls l mypipe
  • prw------- 1 ggrevera ggrevera 0 Oct 5 2130
    mypipe
  • ls l gt mypipe
  • Hangs! Why? Because it waits for the reader.
  • Ctrl-c
  • ls l gt mypipe
  • cat lt mypipe
  • Doesnt hang! Why? Because the reader executes.
  • Output on next slide.

22
Output from named pipe example
  • ls l gt mypipe
  • cat lt mypipe
  • total 106412
  • -rwx------ 1 ggrevera ggrevera 14215 Oct
    5 2045 a.out
  • drwx------ 5 ggrevera ggrevera 4096 Feb
    3 2006 csc4025
  • drwx------ 4 ggrevera ggrevera 4096 Oct
    3 0959 csc4035
  • -rw------- 1 ggrevera ggrevera 194560 Sep
    6 1252 csc4035.tar
  • -rw------- 1 ggrevera ggrevera 891 Dec
    4 2005 dir.cpp
  • .
  • .
  • .
  • -rw------- 1 ggrevera ggrevera 283 Oct
    5 2044 sig.cpp
  • 1 Done ls -l gtmypipe
  • Why did this finish? Because the reader reads
    everything.

23
Named pipes (Windows)
  • CreatePipe
  • Creates an anonymous pipe.
  • CreateNamedPipe
  • Creates an instance of a named pipe and returns a
    handle for subsequent pipe operations. A client
    process connects to a named pipe by using the
    CreateFile or CallNamedPipe function.
  • CallNamedPipe
  • Connects to a message-type pipe, writes to and
    reads from the pipe, and then closes the pipe.
  • TransactNamedPipe
  • Combines the functions that write a message to
    and read a message from the specified named pipe
    into a single network operation.

24
Sockets
25
Sockets
  • Communications between systems across the network!

26
Sockets client-side
  • Steps
  • socket()
  • creates an endpoint for communication and returns
    a descriptor
  • connect()
  • attempts to make a connection to another socket
  • call read() and/or write()
  • similar to an ordinary file

27
Sockets
  • Grand list of standard port numbers
  • http//en.wikipedia.org/wiki/List_of_TCP_and_UDP_
    port_numbers

28
Demo
  • Run cmd (the Windows command prompt).
  • telnet www.google.com 80
  • getltentergt
  • GETltentergt
  • Note HTTP (HyperText Transfer Protocol) is case
    sensitive!

29
Sockets client side
30
Sockets client-side(writes a message and reads
a response)
  • //------------------------------------------------
    ----------------------
  • // g -O2 -o client.exe client.cpp -lsocket
    -lnsl
  • //------------------------------------------------
    ----------------------
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • include ltstrings.hgt
  • include ltsys/socket.hgt
  • include ltnetinet/in.hgt
  • include ltunistd.hgt
  • include ltnetdb.hgt
  • include ltsys/types.hgt
  • //------------------------------------------------
    ----------------------
  • static void error ( char msg )
  • perror( msg )
  • exit( 0 )
  • //------------------------------------------------
    ----------------------
  • int main ( int argc, char argv )

31
Sockets client-side
  • .
  • .
  • .
  • //get host name from command line
  • struct hostent server gethostbyname( argv1
    )
  • if (server NULL)
  • fprintf( stderr, "ERROR, no such host \n" )
  • exit( 0 )
  • struct sockaddr_in serv_addr
  • memset( serv_addr, sizeof(serv_addr), 0 )
  • serv_addr.sin_family AF_INET
  • memcpy( serv_addr.sin_addr.s_addr,
    server-gth_addr, server-gth_length )
  • serv_addr.sin_port htons( portno )
  • if (connect(sockfd, (struct sockaddr)serv_addr,
    sizeof(serv_addr)) lt 0)
  • error( "ERROR connecting" )

Mention memset and memcpy.
32
Sockets client-side
  • .
  • .
  • .
  • printf( "Please enter the message " )
  • char buffer256
  • memset( buffer, sizeof(buffer), 0 )
  • fgets( buffer, sizeof(buffer)-1, stdin )
  • //fgets includes \n, so we'll remove it (if
    necessary)
  • if (strlen(buffer) gt 0 bufferstrlen(buffer
    )-1 '\n')
  • buffer strlen(buffer)-1 0
  • int n write( sockfd, buffer,
    strlen(buffer)1 ) //1 to include \0
  • if (n lt 0) error( "ERROR writing to
    socket" )
  • memset( buffer, sizeof(buffer), 0 )
  • n read( sockfd, buffer, sizeof(buffer)-1 )
  • if (n lt 0) error( "ERROR reading from
    socket" )
  • printf( "response s \n", buffer )

33
Sockets client-side (complete code)
  • //------------------------------------------------
    ----------------------
  • // g -O2 -o client.exe client.cpp -lsocket
    -lnsl
  • //------------------------------------------------
    ----------------------
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • include ltstrings.hgt
  • include ltsys/socket.hgt
  • include ltnetinet/in.hgt
  • include ltunistd.hgt
  • include ltnetdb.hgt
  • include ltsys/types.hgt
  • //------------------------------------------------
    ----------------------
  • static void error ( char msg )
  • perror( msg )
  • exit( 0 )
  • //------------------------------------------------
    ----------------------
  • int main ( int argc, char argv )

34
Sockets server side
35
Sockets server-side
36
Sockets server-side
  • Steps
  • socket()
  • creates an endpoint for communication and returns
    a descriptor
  • bind()
  • this is called "assigning a name to a socket"
  • when a socket is created with socket, it exists
    in a name space (address family) but has no name
    assigned
  • listen()
  • To accept connections, a socket is first
    created with socket(), a willingness to accept
    incoming connections and a queue limit for
    incoming connections are specified with listen,
    and then the connections are accepted with
    accept().
  • repeat forever
  • accept()
  • fork() a child process that performs reads and/or
    writes as per ordinary file.

37
int accept ( int s, struct sockaddr addr,
socklen_t addrlen )
  • It . . .
  • extracts the first connection request on the
    queue of pending connections,
  • creates a new connected socket with mostly the
    same properties as s,
  • and allocates a new file descriptor for the
    socket, which is returned.
  • The newly created socket is no longer in the
    listening state.
  • The original socket s is unaffected by this call.

38
Sockets server-side
  • /
  • \file server2.cpp
  • \author george j. grevera
  • \brief A simple server in the internet domain
    using TCP. Runs on
  • polaris (but not on scott).
  • To compile g -o server2.exe
    server2.cpp -lsocket
  • /
  • include ltassert.hgt
  • include ltnetinet/in.hgt
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • include ltstring.hgt
  • include ltsys/socket.hgt
  • include ltunistd.hgt
  • static const int Port 8090
  • static const bool Verbose true
  • //------------------------------------------------
    ----------------------
  • int main ( int argc, char argv )

39
Sockets server-side
  • //assign a name to the socket
  • struct sockaddr_in serv_addr
  • memset( serv_addr, 0, sizeof(serv_addr) )
  • serv_addr.sin_family AF_INET
  • serv_addr.sin_addr.s_addr INADDR_ANY
  • serv_addr.sin_port htons( Port )
  • if (Verbose) printf( "bind() port d. \n",
    Port )
  • int ret bind( sockfd, (struct
    sockaddr)serv_addr, sizeof(serv_addr) )
  • assert( ret ! -1 )

40
Sockets server-side
  • //a willingness to accept incoming
    connections and a queue
  • // limit for incoming connections are
    specified with listen
  • if (Verbose) puts( "listen()" )
  • ret listen( sockfd, 5 )
  • assert( ret ! -1 )

41
Sockets server-side
  • for ( )
  • //extract the first connection request on
    the queue of
  • // pending connections, create a new
    connected socket with
  • // mostly the same properties as s, and
    allocate a new file
  • // descriptor for the socket, which is
    returned
  • if (Verbose) puts( "parent accept()"
    )
  • struct sockaddr_in cli_addr
  • socklen_t clilen sizeof( cli_addr )
  • int newsockfd accept( sockfd, (struct
    sockaddr)cli_addr, clilen )
  • assert( newsockfd ! -1 )
  • if (Verbose) puts( "parent fork()" )
  • int pid fork()
  • if (pid0)
  • ltchild process code heregt
  • close( newsockfd ) //back in parent

if (Verbose) puts( "child begin
after fork()" ) close( sockfd )
char buffer 256 memset(
buffer, 0, sizeof(buffer) ) if
(Verbose) puts( "child read()" )
int n read( newsockfd, buffer,
sizeof(buffer)-1 ) assert( n ! -1
) if (Verbose)
printf( "child here is the message s \n",
buffer ) puts( "child write()"
) char msg "I got
your message." n write( newsockfd,
msg, strlen(msg)1 ) //1 to include \0
assert( n ! -1 ) close(
newsockfd ) if (Verbose) puts(
"child end" ) exit( 0 ) //end
child
42
Sockets server-side (complete code)
  • /
  • \file server2.cpp
  • \author george j. grevera
  • \brief A simple server in the internet domain
    using TCP. Runs on
  • polaris (but not on scott).
  • To compile g -o server2.exe
    server2.cpp -lsocket
  • /
  • include ltassert.hgt
  • include ltnetinet/in.hgt
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • include ltstring.hgt
  • include ltsys/socket.hgt
  • include ltunistd.hgt
  • static const int Port 8090
  • static const bool Verbose true
  • //------------------------------------------------
    ----------------------
  • int main ( int argc, char argv )

43
Demo
  • Run server on one system (brunel).
  • ./server2.exe
  • Waits for a message from the client, and then
    responds.
  • Run client (on same or different system).
  • ./client.exe brunel 8090
  • Prompts for a message, sends message to server,
    and then outputs response message from server.

44
Message Queues
45
Message queues (Unix/Linux)
  • include ltsys/types.hgt
  • include ltsys/ipc.hgt
  • include ltsys/msg.hgt
  • MSGMAX (Linux) defines the max length of a
    message (8K).
  • Define your message(s).
  • You may define many different messages of
    different lengths.
  • struct myMessage
  • long mtype //message type
  • //body of message (you decide)

46
Message queues (Unix/Linux)
  • msgget - begin accessing (and create if
    necessary) a message queue
  • int msgget ( key_t key, int msgflg )
  • msgsnd - send (enqueue) a message
  • int msgsnd ( int msqid, struct msgbuf msgp,
  • size_t msgsz, int msgflg )
  • msgrcv - receive (dequeue) a message
  • ssize_t msgrcv ( int msqid, struct msgbuf
    msgp,
  • size_t msgsz, long msgtyp, int msgflg )
  • msgctl - misc. message queue control

47
Example
  • //file m.h
  • //declare the message structure
  • typedef struct
  • enum mTypeA, mTypeB, mTypeC
  • long mtype
  • char mtext 256
  • message_buf
  • define KEY 1234

48
Example (sender)
  • //file mtx.cpp
  • include ltsys/types.hgt
  • include ltsys/ipc.hgt
  • include ltsys/msg.hgt
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • include ltstring.hgt
  • include "m.h"
  • int main ( int argc, char argv )
  • // Get the message queue id for the "name"
    1234, which was created by
  • // the server.
  • key_t key KEY
  • int msgflg IPC_CREAT 0666
  • fprintf( stderr, "\nmsgget Calling
    msgget(lx,o) \n", key, msgflg )
  • int msqid
  • if ((msqid msgget(key, msgflg)) lt 0)
  • fprintf( stderr, "msgget msgget succeeded
    msqid d \n", msqid )
  • // We'll send message type B
  • message_buf sbuf
  • sbuf.mtype sbuf.mTypeB
  • strcpy( sbuf.mtext, "Did you get this?" )
  • //size_t buf_length strlen(sbuf.mtext) 1
  • size_t buf_length sizeof( message_buf )
  • // Send a message.
  • if (msgsnd(msqid, sbuf, buf_length,
    IPC_NOWAIT) lt 0)
  • printf( "d, d, s, d\n", msqid,
    sbuf.mtype, sbuf.mtext, buf_length )
  • perror( "msgsnd" )
  • exit( 1 )
  • printf( "Message \"s\" Sent \n", sbuf.mtext
    )
  • return 0

49
Example (receiver)
  • //file mrx.cpp
  • include ltsys/types.hgt
  • include ltsys/ipc.hgt
  • include ltsys/msg.hgt
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • include "m.h"
  • int main ( int argc, char argv )
  • // Get the message queue id for the "name"
    KEY, which was created by
  • // the server.
  • int msqid msgget( KEY, 0666 )
  • if (msqid lt 0)
  • perror( "msgget" )
  • exit( 1 )
  • // Receive an answer of message type B.
  • message_buf rbuf
  • if (msgrcv(msqid, rbuf, sizeof(rbuf), 0, 0)
    lt 0)
  • perror( "msgrcv" )
  • exit( 1 )
  • // Print the answer.
  • printf( "d s \n", rbuf.mtype, rbuf.mtext )
  • exit( 0 )

50
Message queues (Windows)
  • Call MQOpenQueue to open the queue with send
    access.
  • Call MQSendMessage to send the message.
  • The MQReceiveMessage function allows you to read
    messages . When reading messages, you can either
    peek at (not removing them) or retrieve the
    messages (removing them) in the queue. Messages
    can be read either synchronously, asynchronously,
    or through a transaction.
  • Call MQCloseQueue to close the opened queue and
    free resources.

51
Demo (Unix)
  • mtx.exe
  • Creates queue (if necessary, so run first).
  • Queues up one message.
  • mrx.exe
  • Dequeues a message (waits, otherwise).

52
Other IPC Mechanisms
53
Other IPC mechanisms
  • Monitors
  • A collection of procedures, variables, and data
    structures that are all grouped together in a
    special kind of module or package.
  • Only one process can be active in a monitor at
    any instant.

54
Monitors and the (bounded) producer-consumer
problem
55
Where do we see monitors?
  • The Java programming language provides two basic
    synchronization idioms synchronized methods and
    synchronized statements.
  • - from http//download.oracle.com/javase/tutorial/
    essential/concurrency/syncmeth.html

56
Where do we see monitors?
  • Synchronization is built around an internal
    entity known as the intrinsic lock or monitor
    lock. (The API specification often refers to
    this entity simply as a "monitor.")
  • - from http//download.oracle.com/javase/tutorial/
    essential/concurrency/locksync.html

57
Java support . . .
  1. synchronized methods
  2. synchronized statements (blocks)

58
Synchronized methods
59
Synchronized methods
  • To make a method synchronized, simply add the
    synchronized keyword to its declaration
  • public class SynchronizedCounter
  • private int c 0
  • public synchronized void increment ( )
    c
  • public synchronized void decrement ( )
    c--
  • public synchronized int value ( ) return
    c
  • If count is an instance of SynchronizedCounter,
    then making these methods synchronized has two
    effects
  • First, it is not possible for two invocations of
    synchronized methods on the same object to
    interleave. When one thread is executing a
    synchronized method for an object, all other
    threads that invoke synchronized methods for the
    same object block (suspend execution) until the
    first thread is done with the object.
  • Second, when a synchronized method exits, it
    automatically establishes a happens-before
    relationship with any subsequent invocation of a
    synchronized method for the same object. This
    guarantees that changes to the state of the
    object are visible to all threads.
  • - from http//download.oracle.com/javase/tutorial/
    essential/concurrency/syncmeth.html

60
Locks in synchronized methods
  • When a thread invokes a synchronized method, it
    automatically acquires the intrinsic lock for
    that method's object and releases it when the
    method returns.
  • The lock release occurs even if the return was
    caused by an uncaught exception.
  • - from http//download.oracle.com/javase/tutorial/
    essential/concurrency/locksync.html

61
Locks in synchronized methods
  • You might wonder what happens when a static
    synchronized method is invoked, since a static
    method is associated with a class, not an object.
  • In this case, the thread acquires the intrinsic
    lock for the Class object associated with the
    class.
  • Thus access to class's static fields is
    controlled by a lock that's distinct from the
    lock for any instance of the class.
  • - from http//download.oracle.com/javase/tutorial/
    essential/concurrency/locksync.html

62
Synchronized statements
63
Synchronized statements
  • public void addName ( String name )
  • synchronized (this)
  • lastName name
  • nameCount
  • nameList.add( name )
  • public class MsLunch
  • private long c1 0
  • private long c2 0
  • private Object lock1 new Object()
  • private Object lock2 new Object()
  • public void inc1 ( )
  • synchronized (lock1)
  • c1
  • public void inc2 ( )
  • synchronized (lock2)
  • c2

Locks taken out on two different objects for
finer control.
Single lock taken out on this entire object
(instance).
64
Other IPC mechanisms
  • Message passing (MPI)
  • Barriers (also implemented in MPI and the pthread
    library)
About PowerShow.com