0% found this document useful (0 votes)
90 views56 pages

Chapter Three: Inter-Thread and Inter-Process Communication

Inter-thread communication allows synchronized threads to communicate with each other through approaches like wait(), notify(), and notifyAll(). Inter-process communication involves the exchange of data between independent processes through operating system resources like message queues and shared memory. Common IPC types include unicast from one process to another and multicast from one process to multiple processes. Synchronization between communicating processes can be achieved through synchronous or asynchronous send and receive operations.

Uploaded by

Murad Amine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views56 pages

Chapter Three: Inter-Thread and Inter-Process Communication

Inter-thread communication allows synchronized threads to communicate with each other through approaches like wait(), notify(), and notifyAll(). Inter-process communication involves the exchange of data between independent processes through operating system resources like message queues and shared memory. Common IPC types include unicast from one process to another and multicast from one process to multiple processes. Synchronization between communicating processes can be achieved through synchronous or asynchronous send and receive operations.

Uploaded by

Murad Amine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Chapter Three

Inter-thread and Inter-process


communication

Wolkite University By: Yaregal N.

1
Topic to be covered

 Inter-thread communication
 Inter-process communication
 IPC Approaches/Types
Inter-thread Communication
3

• Is all about allowing synchronized threads to communicate with each

other.

• Is a mechanism in which a thread is paused running in its critical

section and another thread is allowed to enter (or lock) in the same

critical section to be executed.


4

 Can be implemented through three approaches:


1. wait(): Causes current thread to release the lock and wait until either
another thread invokes the notify method.
2. notify():Wakes up a single thread that is waiting on this object's
monitor.
3. notifyAll(): Wakes up all threads that are waiting on this object's
monitor.
5

 Example: Inter-thread communication


How it Works
6

 Threads enter to acquire lock.


 Lock is acquired by on thread.
 Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
 If you call notify() or notifyAll() method, thread moves to the notified
state (runnable state).
 Now thread is available to acquire lock.
 After completion of the task, thread releases the lock and exits the
monitor state of the object
Inter process Communications
 Exchange of data between two or more separate,
independent processes/threads.
 Operating systems provide facilities/resources for inter-

process communications (IPC), such as message queues,


semaphores, and shared memory.
 Distributed computing systems make use of these

facilities/resources to provide application programming


interface (API) which allows IPC to be programmed at a
higher level of abstraction. (e.g., send and receive)
 Distributed computing requires information to be
exchanged among independent processes.
IPC – unicast and multicast
 In distributed computing, two or more processes engage
in IPC using a protocol agreed upon by the processes.
A process may be a sender at some points during a
protocol, a receiver at other points.
 When communication is from one process to a single
other process, the IPC is said to be a unicast, e.g.,
Socket communication.
 When communication is from one process to a group of
processes, the IPC is said to be a multicast, e.g.,
Publish/Subscribe Message model,
Unicast vs. Multicast

P2 P2 P3 ... P4

m
m m m

P1 P1

uni c as t m ul ti c as t
Publish/Subscribe Message model

 The publish/subscribe communication paradigm:


 Publishers: produce data in the form of events.
 Subscribers: declare interests on published data with subscriptions.
 Each subscription is a filter on the set of published events.
 An Event Notification Service (ENS) notifies to each subscriber
every published event that matches at least one of its subscriptions.
IPCs in Distributed Computing

P roc es s 1 P roc es s 2

data

s ender rec eiver


Operations provided in an archetypal IPCs
API

 Consider a basic API that provides the minimum level of abstraction to


facilitate IPC. Four primitive operations are needed. They are:
1. Send ( [receiver], message)
2. Receive ( [sender], message storage object)
3. Connect (sender address, receiver address), for connection
oriented communication.
4. Disconnect (connection identifier), for connection-oriented
communication.
Inter process Communication in basic HTTP

 Network service protocols can be implemented using primitive IPC


operations.
 For example, in basic HTTP (used extensively on the WWW), one process
and a Web browser issues a connect operation to establish a logical
connection to another process.
 A Web server, followed by a send operation to the Web server, transmits
data representing a request.
 The Web server process in turn issues a send operation that transmits data
requested by the Web browser process.
 At the end of the communication, each process issues a disconnect
operation to terminate the connection. 
Inter process Communication in basic HTTP
Event Synchronization
 A main difficulty with IPC is to execute multiple processes involved in a
system independently, with neither process knowing what takes place in
the process at the other end.
 Inter-process communication may require that the two processes
synchronize their operations: one side sends, then the other receives until
all data has been sent and received.
 Ideally, the send operation starts before the receive operation
commences (start).
 In practice, the synchronization requires system support.
Synchronous vs. Asynchronous Communication

 The IPC operations may provide the synchronization necessary


using blocking.
 A blocking operation issued by a process will block further
processing of the process until the operation is fulfilled.
 Alternatively, IPC operations may be asynchronous or non-
blocking.
 An asynchronous operation issued by a process will not block
further processing of the process. Instead, the process is free to
proceed with its processing, and may optionally be notified by the
system when the operation is fulfilled.
Types of IPC Operations

 Synchronous Send and Synchronous Receive


 Asynchronous Send and Synchronous Receive
 Synchronous Send and Asynchronous Receive
 Asynchronous Send and Asynchronous Receive
Synchronous send and receive

 A receive operation issued causes the suspension of the issuing process (process
2) until data is received to fulfill the operation.
 A send operation issued causes the sending process (process 1) to suspend.
 When the data sent has been received by process2, the IPC facility on host 2
sends an acknowledgment to the IPC facility on host I, and process 1 may
subsequently be unblocked.
 Depending on the implementation of the IPC facility, the synchronous receive
operation may not be fulfilled until the amount of data the receiver expects to
receive has arrived.
 The use of synchronous send and synchronous receive is warranted if the
application logic of both processes requires that the data sent must be received
before further processing can proceed.
Synchronous send and receive

pr o c e s s 1 pro cess 2
r u nn i ng o n ho s t 2
r u n ni ng o n ho s t 1 Event Diagram

b lo c k in g r ec eiv e s ta r ts

b lo c k in g s en d s tar ts an o p er a tio n

ex ec u tio n f lo w
ac k n o w led g em en t o f d a ta r ec eiv e d s u s p en d ed p er io d
b lo c k in g s en d r etu r n s p r o v id ed b y th e I P C f ac ility b lo c k in g r ec eiv e en d s

Syn c h r o no us Se n d an d R e c e i ve

Client Server
Sender Receiver
Asynchronous send and Synchronous receive

 A receive operation issued will cause the suspension of the issuing


process until data is received to fulfill the operation.
 A send operation issued will not cause the sending process to
suspend. In this case the sending process is never blocked, so no
acknowledgment is necessary from the IPC facility on the host of
process 2, if the sender's application logic does not depend on the
receiving of the data at the other end.
 Depending on the implementation of the IPC facility, there is no
guarantee that the data sent will actually be delivered to the receiver. 
Asynchronous send and Synchronous receive

P rocess 2
P rocess 1 Event Diagram

b lo c k in g r e c e iv e s ta r ts

n o n b lo c k in g s e n d

o p e r a tio n
e x e c u tio n f lo w
s u s p e n d e d p e r io d
b lo c k in g r e c e iv e r e tu r n s

As yn c h r o n o u s S e n d an d
S yn c h r o n o u s R e c e i ve

Client Server
Sender Receiver
Synchronous send and Asynchronous Receive

 An asynchronous receive operation causes no blocking of the


process that issues the operation, and the outcome will depend
on the implementation of the IPC facility.
 The receive operation will, in all cases, return immediately.  
 There are three scenarios for what happens subsequently:
Synchronous send and Asynchronous Receive - 1

• The data requested by the receive P rocess 1


P rocess 2

operation has already arrived at the


time when the receive operation is
issued. b lo c k in g s en d is s u ed

• The data is delivered to process 2 n o n b lo c k in g r ec eiv e is s u ed


tr an s p ar en t ac k n o w led g em en t
immediately and an acknowledgment p r o v id ed b y th e I P C f ac ility ex ec u tio n flo w
s u s p en d ed p er io d
from host 2's IPC facility will
unblock process 1.
Sync hr o no us Se nd and
As ync hr o no us R e c e i ve
S ce n ario A

Data from P1 was received by P2


before issuing a non-blocking receive op in P2
Synchronous send and Asynchronous Receive - 2

P rocess 2
• The data requested by the receive P rocess 1

operation has not yet arrived and thus no


data is delivered to the process. n o n b lo c k in g r ec eiv e is s u ed
an d retu rn ed im m ed iately

• It is the receiving process's responsibility b lo c k in g s en d is s u ed

to confirm that it has indeed received the in d efin ite


ex ec u tio n f lo w
data and repeat the receive operation until b lo c k in g
s u s p en d ed p erio d

the data has arrived.


P rocess 2
• P1 is blocked indefinitely until P2 P r o c e ss 1 Sync hr o no us Se nd and
reissues a receive request and an As ync hr o no us R e c e i ve
S ce n a rio B
acknowledgment eventually arrives from
host 2's IPC facility. Data from P1 arrived to P2 after P2 issued a
non-blocking receive op
Synchronous send and Asynchronous Receive - 3

• The data requested by the receive P ro cess 2


operation has not yet arrived. P ro cess 1

• The IPC facility of host 2 will notify


process 2 when the data it requested has n o n b lo c k in g rec eiv e is s u ed
an d r etu r n ed im m ed iately

arrived, at which point process 2 may b lo c k in g s en d is s u ed


p ro c es s is n o tif ied
proceed to process the data. tr an s p aren t ac k n o w led g em en t
p r o v id ed b y th e IP C f ac ility
o f th e ar r iv al o f
d ata
ex ec u tio n flo w
• This scenario requires that process 2 s u s p en d ed p erio d

provide a listener or event handler that


can be invoked by the IPC facility to Sync hr o no us Se nd and
notify the process of the arrival of the As ync hr o no us R e c e i ve
S ce n a rio C

requested data.
Data from P1 arrived to P2 before P2 issues a non-blocking receive op. P2 is
notified of the arrival of data
Asynchronous send and Asynchronous receive

 Without blocking on either side, the only way that the data can be
delivered to the receiver is if the IPC facility retains the data received.
 The receiving process can then be notified of the data's arrival.
 Alternatively, the receiving process may poll for the arrival of the
data and process it when the awaited data has arrived.
Asynchronous send and Asynchronous receive

P rocess 2
P r o c e ss 1

n o n b lo c k in g r ec eiv e is s u ed
an d retu r n ed im m ed iately
b lo c k in g s en d is s u ed
p r o c es s is n o tif ied
o f th e ar r iv al o f
d ata
ex ec u tio n f lo w
s u s p en d ed p erio d

As ync hr o no us Se nd and
As ync hr o no us R e c e i ve
S ce n a rio C

Does P1 need an acknowledgement from P2?


IPC Approaches
Method Short Description Provided by

File A record stored on disk, or a record synthesized on Most operating systems


demand by a file server, which can be accessed by
multiple processes.

Signal A system message sent from one process to another, Most operating systems
not usually used to transfer data but instead used to
remotely command the partnered process.

Socket A data stream sent over a network interface, either to Most operating systems
a different process on the same computer or to
another computer on the network. Typically byte-
oriented, sockets rarely preserve message boundaries.
Data written through a socket requires formatting to
preserve message boundaries.

Shared Multiple processes are given access to the same All POSIX systems, Windows
memory block of memory which creates a shared buffer for
the processes to communicate with each other.
What is a socket?
 Socket
• The combination of an IP address and a port number. (RFC 793 ,original
TCP specification)
• The name of the Berkeley-derived application programming interfaces
(APIs) for applications using TCP/IP protocols.
• Two types
• Stream socket : reliable two-way connected communication streams
• Datagram socket
 Socket pair
 Specified the two end points that uniquely identifies each TCP
connection in an internet.
 4-tuple: (client IP address, client port number, server IP address, server
port number)
Socket Programming with TCP

Figure : Processes communicating through TCP sockets

The application developer has the ability to fix a few TCP


parameters, such as maximum buffer and maximum segment sizes.
Sockets for server and client
 Server
 Welcoming socket
 Welcomes some initial contact from a client.
 Connection socket
 Is created at initial contact of client.
 New socket that is dedicated to the particular client.
 Client
 Client socket
 Initiate a TCP connection to the server by creating a socket
object. (Three-way handshake)
 Specify the address of the server process, namely, the IP
address of the server and the port number of the process.
Socket functional calls

 socket (): Create a socket


 bind(): bind a socket to a local IP address and port #
 listen(): passively waiting for connections
 connect(): initiating connection to another socket
 accept(): accept a new connection
 Write(): write data to a socket
 Read(): read data from a socket
 sendto(): send a datagram to another UDP socket
 recvfrom(): read a datagram from a UDP socket
 close(): close a socket (tear down the connection)
Sockets

Figure 2.6-2: Client socket, welcoming socket and connection socket


Socket-programming using TCP
TCP service: reliable byte stream transfer

socket( )
bind( ) server
socket( ) listen( )
client bind( )
connect( ) TCP conn. request
accept( )
send( ) TCP ACK
recv( )

recv( )
send( )
close( ) close( )

controlled by
application process
process
developer socket
socket
controlled by TCP with
TCP with
operating buffers, internet
system buffers,
variables
variables
Socket programming with TCP
keyboard monitor

Example client-server app:


 client reads line from standard input

inFromUser
input
stream
(inFromUser stream) , sends to Client
server via socket (outToServer Process Input stream:
process sequence of bytes
stream) output stream: into process
 server reads line from socket sequence of bytes
out of process
 server converts line to uppercase,

inFromServer
outToServer
output input
sends back to client stream stream

 client reads, prints modified line from


client TCP
clientSocket
socket (inFromServer stream) socket TCP
socket

to network from network


Client/server socket interaction: TCP

Server (running on hostid) Client


create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
connectionSocket = clientSocket =
welcomeSocket.accept() Socket()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
JAVA TCP Sockets
 In Package java.net
 java.net.Socket
 Implements client sockets (also called just “sockets”).
 An endpoint for communication between two machines.
 Constructor and Methods
 Socket(String host, int port): Creates a stream socket and connects it to the specified port number on
the named host.
 InputStream getInputStream()
 OutputStream getOutputStream()
 close()
 java.net.ServerSocket
 Implements server sockets.
 Waits for requests to come in over the network.
 Performs some operation based on the request.
 Constructor and Methods
 ServerSocket(int port)
 Socket Accept(): Listens for a connection to be made to this socket and accepts it. This method blocks
until a connection is made.
Establishing a Simple Server Using Stream
Sockets
 Step 1: Create a ServerSocket
ServerSocket server = new ServerSocket( portNumber, queueLength );
 Step 2: Wait for a Connection
Socket connection = server.accept();
 Step 3: Get the Socket’s I/O Streams
ObjectInputStream input = new
ObjectInputStream( connection.getInputStream() );
ObjectOutputStream output = new
ObjectOutputStream( connection.getOutputStream() );
 Step 4: Perform the Processing
in which the server and the client communicate via the OutputStream and
InputStream objects.
Cont…
 Step 5: Close the Connection
when the transmission is complete, the server
closes the connection by invoking the close
method on the streams and on the Socket.
Establishing a simple client in Java
 Step 1: Create a Socket to Connect to the Server
Socket connection = new Socket( serverAddress, port );
 Step 2: Get the Socket’s I/O Streams

the client uses Socket methods getInputStream and


getOutputStream to obtain references to the Socket’s
InputStream and OutputStream.
 Step 3: Perform the Processing

is the processing phase in which the client and the server


communicate via the InputStream and OutputStream
objects.
Cont….
 Step 4: Close the Connection
the client closes the connection when the
transmission is complete by invoking the close
method on the streams and on the Socket
TCPClient.java

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class cli {
public static void main(String args[]) throws UnknownHostException, IOException{
int number,temp;
Scanner sc=new Scanner (System.in);
Socket s=new Socket("127.0.0.1",1342);
Scanner sc1=new Scanner (s.getInputStream());
System.out.println("Enter any number");
number=sc.nextInt();
PrintStream p=new PrintStream(s.getOutputStream());
p.println(number);
temp=sc1.nextInt();
System.out.println(temp);
}}
TCPServer.java
import java.io.IOException;
import java.net.ServerSocket;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ser {
public static void main(String args[]) throws IOException{
int number,temp;
ServerSocket s1=new ServerSocket(1342);
Socket ss=s1.accept();
Scanner sc=new Scanner(ss.getInputStream());
number=sc.nextInt();
temp=number*2;
PrintStream p=new PrintStream(ss.getOutputStream());
p.println(temp);
}}
Socket Programming with UDP
 UDP
 Connectionless and unreliable service.
 There isn’t an initial handshaking phase.
 Doesn’t have a pipe.
 transmitted data may be received out of order, or lost
 Socket Programming with UDP
 No need for a welcoming socket.
 No streams are attached to the sockets.
 the sending hosts creates “packets” by attaching the IP destination address
and port number to each batch of bytes.
 The receiving process must unravel to received packet to obtain the
packet’s information bytes.
Client/server socket interaction: UDP

Server (running on hostid) Client

create socket,
create socket,
port=x, for clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket
read request from
serverSocket

write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port umber close
clientSocket
Example: Java client (UDP)

keyboard monitor

inFromUser
input
stream

Client
Process
Input: receives
process
packet (TCP
received “byte
Output: sends
stream”)
packet (TCP sent

receivePacket
sendPacket
“byte stream”) UDP UDP
packet packet

client UDP
clientSocket
socket UDP
socket

to network from network


JAVA UDP Sockets

 In Package java.net
 java.net.DatagramSocket
 A socket for sending and receiving datagram packets.
 Constructor and Methods
 DatagramSocket(int port): Constructs a datagram socket and binds it to the
specified port on the local host machine.
 void receive( DatagramPacket p)
 void send( DatagramPacket p)
 void close()
UDPClient.java
import java.net.*;
import java.io.*;

public class udpclient {

public static void main(String args[])throws Exception {

DatagramSocket ds = new DatagramSocket();


byte[] b = "this is udp".getBytes();
InetAddress ip = InetAddress.getByName("localhost");
int port = 2000;
DatagramPacket dp = new DatagramPacket(b, b.length, ip, 2000);
ds.send(dp);
}
}
UDPServer.java

import java.net.*;
import java.io.*;
public class updserver {
public static void main(String args[]) throws Exception {
DatagramSocket ds=new DatagramSocket(2000);
byte [] b=new byte[100];

DatagramPacket dp=new DatagramPacket(b,b.length);


ds.receive(dp);
String msg=new String(b);
System.out.println("Received"+msg);
}

}
Pipes

 Acts as a conduit allowing two processes to communicate.


 Some issues:
 Is communication unidirectional or bidirectional?
 In the case of two-way communication, is it half
or full-duplex?
 Must there exist a relationship (i.e., parent-child) between
the communicating processes?
 Can the pipes be used over a network?
Ordinary Pipes
 Ordinary Pipes allow communication in standard
producer-consumer style.
 Producer writes to one end (the write-end of
the pipe).
 Consumer reads from the other end (the read-end of
the pipe).
 Ordinary pipes are therefore unidirectional.
 Require parent-child relationship between
communicating processes.
Ordinary Pipes
Named Pipes

 Named Pipes are more powerful than ordinary pipes.


 Communication is bidirectional.
 No parent-child relationship is necessary between the communicating
processes.
 Several processes can use the named pipe for communication.
 Provided on both UNIX and Windows systems.
Shared Memory
• In the shared – memory model, a region of memory that is shared
by cooperating processes is established.
• Processes can then exchange information by reading and writing
data to the shared region.
Message Passing
• In the message passing model, communication takes place by
means of messages exchanged between the cooperating processes.
Thank You ...

“The most common miracles of software engineering are the


transitions from analysis to design and design to code.”
Richard Dué

You might also like