D Programming Concurrency - D Programming Language

What is D Programming Concurrency?

Concurrency is constructing a program run on multiple threads at a time. An instance of a concurrent program is a web server replying many clients at the same time. Concurrency is easy with message passing but very problematic to write if they are based on data sharing.
Data that is passed between threads are called messages. Messages may be composed of any type and any number of variables. Every thread has an id, which is used for requiring recipients of messages. Any thread that starts another thread is called the owner of the new thread.

Initiating Threads in D

The function spawn() takes a pointer as a parameter and starts a new thread from that function. Any processes that are carried out by that function, including other functions that it may call, would be executed on the new thread. The owner and the worker both start executing separately as if they were independent programs.

Example

When the above code is compiled and executed, it reads the file created in previous section and produces the following result –

Thread Identifiers in D

The thisTid variable available globally at the module level is always the id of the current thread. Also you can receive the threadId when spawn is called. An example is shown below.

Example

When the above code is compiled and executed, it reads the file created in previous section and produces the following result –

Message Passing in D

The function send() sends messages and the function receiveOnly() waits for a message of a particular type. There are other functions named prioritySend(), receive(), and receiveTimeout(), which are explained later.

The owner in the following program sends its worker a message of type int and waits for a message from the worker of type double. The threads continue sending messages back and forth until the owner sends a negative int. An example is shown below.

Example

When the above code is compiled and executed, it reads the file created in previous section and produces the following result –

Message Passing with Wait in D

A simple example with the message passing with wait is shown below.

When the above code is compiled and executed, it reads the file created in previous section and produces the following result –

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

D Programming Language Topics