Previous | Next --- Slide 12 of 72
Back to Lecture Thumbnails
rohany

How could we implement an asynchronous send/recieve with a synchronous function?

kayvonf

@rohany. Let's clarify this. Specifically what I asked in lecture was "Would it be valid to correctly implement an asynchronous send or receive API call (a send or a recv) with a call to a synchronous version?"

One immediately answer might be... yes you could, and then the later implementation of the "check if done" would be a no-op.

However, the real answer is that no you cannot. It wouldn't be an async send/receive anymore if you did. The synchronous versions don't return to the caller until the operation is done, so the calling thread must block and cannot proceed concurrently with the operation. If the logic in the calling thread makes assumptions about the async nature of the send operation (that the calling thread would be allowed to proceed and check later for completion), then a program written using async operations could deadlock if the implementation blocked in the call to send. So in fact, I was speaking a little loosely in class.

Question: But could you implement a blocking (synchronous send/receive) given only async versions? If so, how?

rohany

Could the async call block until it has recieved its result, and then return control to the caller?

kayvonf

@rohany. To clarify: Imagine I gave you two functions:

  • An async send: handle_t async_send(int dst, int num_bytes, void* buffer);
  • A check to see if the async send is done: bool check_if_done(handle_t);

Given these two functions, how would you implement a synchronous send: void send(int dst, int num_bytes, void* buffer)?

rohany

I believe it could be done as follows

void send(int dst, int num_bytes, void* buffer){
  handle_t handle = async_send(dst, num_bytes, buffer);
  while(!check_if_done(handle)){}
  return;
}
kayvonf

Yep! Perfect.

paramecinm

@kayvonf You said we cannot implement async send/recv based on sync version. I think we can create a new thread when we need to call send/recv functions. So the main thread won't be blocked by that sync call. We can check if the thread is finished (use semaphore or something similar) to indicate if the send/recv call is finished. Is that right?

SR_94

@paramecinm Let's say we do that. We create a new thread (T1) that does the send for us and sends a signal to the main thread when the send returns. But how is the main thread checking if it has received the signal - in a while loop? That would imply it will still be waiting for T1 to complete the send which makes the entire operation synchronous.

Levy

Check channel and buffered channel in Golang (https://tour.golang.org/concurrency/2), they represent synchronous and asynchronous data sending in communication model