Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book 1.7. Polar to Cartesian—Concurrency

1.7. Polar to Cartesian—Concurrency

One key aspect of the Go language is its ability to take advantage of modern computers with multiple processors and multiple cores, and to do so without burdening programmers with lots of bookkeeping. Many concurrent Go programs can be written without any explicit locking at all (although Go does have locking primitives for when they’re needed in lower-level code, as we will see in Chapter 7).

Two features make concurrent programming in Go a pleasure. First, goroutines (in effect very lightweight threads/coroutines) can easily be created at will without the need to subclass some “thread” class (which isn’t possible in Go anyway). Second, channels provide type-safe one-way or two-way communication with goroutines and which can be used to synchronize goroutines.

The Go way to do concurrency is to communicate data, not to share data. This makes it much easier to write concurrent programs than using the traditional threads and locks approach, since with no shared data we can’t get race conditions (such as deadlocks), and we don’t have to remember to lock or unlock since there is no shared data to protect.

In this section we will look at the fifth and last of the chapter’s “overview” examples. This section’s example program uses two communication channels and does its processing in a separate Go routine. For such a small program this is complete overkill, but the point is to illustrate a basic use of these Go features in as clear and short a way as possible. More realistic concurrency examples that show many of the different techniques that can be used with Go’s channels and goroutines are presented in Chapter 7.

The program we will review is called polar2cartesian; it is an interactive console program that prompts the user to enter two whitespace-separated numbers—a radius and an angle—which the program then uses to compute the equivalent cartesian coordinates. In addition to illustrating one particular approach to concurrency, it also shows some simple structs and how to determine if the program is running on a Unix-like system or on Windows for when the difference matters. Here is an example of the program running in a Linux console:


The program is in file polar2cartesian/polar2cartesian.go, and we will review it top-down, starting with the imports, then the structs it uses, then its init() function, then its main() function, and then the functions called by main(), and so on.


The polar2cartesian program imports several packages, some of which have been mentioned in earlier sections, so we will only mention the new ones here. The math package provides mathematical functions for operating on floating-point numbers (§2.3.2, → 64) and the runtime package provides functions that access the program’s runtime properties, such as which platform the program is running on.


In Go a struct is a type that holds (aggregates or embeds) one or more data fields. These fields can be built-in types as here (float64), or structs, or interfaces, or any combination of these. (An interface data field is in effect a pointer to an item—of any kind—that satisfies the interface, i.e., that has the methods the interface specifies.)

It seems natural to use the Greek lowercase letter theta (θ) to represent the polar coordinate’s angle, and thanks to Go’s use of UTF-8 we are free to do so. This is because Go allows us to use any Unicode letters in our identifiers, not just English letters.

Although the two structs happen to have the same data field types they are distinct types and no automatic conversion between them is possible. This supports defensive programming; after all, it wouldn’t make sense to simply substitute a cartesian’s positional coordinates for polar coordinates. In some cases such conversions do make sense, in which case we can easily create a conversion method (i.e., a method of one type that returned a value of another type) that made use of Go’s composite literal syntax to create a value of the target type populated by the fields from the source type. (Numeric data type conversions are covered in Chapter 2; string conversions are covered in Chapter 3.)


If a package has one or more init() functions they are automatically executed before the main package’s main() function is called. (In fact, init()functions must never be called explicitly.) So when our polar2cartesian program is invoked this init() function is the first function that is called. We use init() to set the prompt to account for platform differences in how end of file is signified—for example, on Windows end of file is given by pressing Ctrl+Z then Enter. Go’s runtime package provides the GOOS (Go Operating System) constant which is a string identifying the operating system the program is running on. Typical values are darwin (Mac OS X), freebsd, linux, and windows.

Before diving into the main() function and the rest of the program we will briefly discuss channels and show some toy examples before seeing them in proper use.

Channels are modeled on Unix pipes and provide two-way (or at our option, one-way) communication of data items. Channels behave like FIFO (first in, first out) queues, hence they preserve the order of the items that are sent into them. Items cannot be dropped from a channel, but we are free to ignore any or all of the items we receive. Let’s look at a very simple example. First we will make a channel:


Channels are created with the make() function (Chapter 7) and are declared using the syntax, chan Type. Here we have created the messages channel to send and receive strings. The second argument to make() is the buffer size (which defaults to 0); here we have made it big enough to accept ten strings. If a channel’s buffer is filled it blocks until at least one item is received from it. This means that any number of items can pass through a channel, providing the items are retrieved to make room for subsequent items. A channel with a buffer size of 0 can only send an item if the other end is waiting for an item. (It is also possible to get the effect of nonblocking channels using Go’s select statement, as we will see in Chapter 7.)

Now we will send a couple of strings into the channel:


When the <-communication operator is used as a binary operator its left-hand operand must be a channel and its right-hand operand must be a value to send to the channel of the type the channel was declared with. Here, we first send the string Leader to the messages channel, and then we send the string Follower.


When the <- communication operator is used as a unary operator with just a right-hand operand (which must be a channel), it acts as a receiver, blocking until it has a value to return. Here, we retrieve two messages from the messages channel. The message1 variable is assigned the string Leader and the message2 variable is assigned the string Follower; both variables are of type string.

Normally channels are created to provide communication between goroutines. Channel sends and receives don’t need locks, and the channel blocking behavior can be used to achieve synchronization.

Now that we have seen some channel basics, let’s see channels—and goroutines —in practical use.


Once any init() functions have returned, Go’s runtime system then calls the main package’s main() function.

Here, the main() function begins by creating a channel (of type chan polar) for passing polarstructs, and assigns it to the questions variable. Once the channel has been created we use a defer statement to call the built-in close() function (→ 185) to ensure that it is closed when it is no longer needed. Next we call the createSolver() function, passing it the questions channel and receiving from it an answers channel (of type chan cartesian). We use another defer statement to ensure that the answers channel is closed when it is finished with. And finally, we call the interact() function with the two channels, and in which the user interaction takes place.


The createSolver() function begins by creating an answers channel to which it will send the answers (i.e., cartesian coordinates) to the questions (i.e., polar coordinates) that it receives from the questions channel.

After creating the channel, the function then has a gostatement. A gostatement is given a function call (syntactically just like a defer statement), which is executed in a separate asynchronous goroutine. This means that the flow of control in the current function (i.e., in the main goroutine) continues immediately from the following statement. In this case the go statement is followed by a return statement that returns the answers channel to the caller. As we noted earlier, it is perfectly safe and good practice in Go to return local variables, since Go handles the chore of memory management for us.

In this case we have (created and) called an anonymous function in the go statement. The function has an infinite loop that waits (blocking its own goroutine, but not any other goroutines, and not the function in which the goroutine was started), until it receives a question—in this case a polarstruct on the questions channel. When a polar coordinate arrives the anonymous function computes the corresponding cartesian coordinate using some simple math (and using the standard library’s math package), and then sends the answer as a cartesian struct (created using Go’s composite literal syntax), to the answers channel.

In (➊) the <- operator is used as a unary operator, retrieving a polar coordinate from the questions channel. And in (➋) the <- operator is used as a binary operator; its left-hand operand being the answers channel to send to, and its right-hand operand being the cartesian to send.

Once the call to createSolver() returns we have reached the point where we have two communication channels set up and where a separate goroutine is waiting for polar coordinates to be sent on the questionschannel—and without any other goroutine, including the one executing main(), being blocked.


This function is called with both channels passed as parameters. It begins by creating a buffered reader for os.Stdin since we want to interact with the user in the console. It then prints the prompt that tells the user what to enter and how to quit. We could have made the program terminate if the user simply pressed Enter (i.e., didn’t type in any numbers), rather than asking them to enter end of file. However, by requiring the use of end of file we have made polar2cartesian more flexible, since it is also able to read its input from an arbitrary external file using file redirection (providing only that the file has two whitespace-separated numbers per line).

The function then starts an infinite loop which begins by prompting the user to enter a polar coordinate(a radiusandan angle).After asking for theuser’sinput the function waits for the user to type some text and press Enter, or to press Ctrl+D (or Ctrl+Z, Enter on Windows) to signify that they have finished. We don’t bother checking the error value; if it isn’t nil we break out of the loop and return to the caller (main()), which in turn will return (and call its deferred statements to close the communication channels).

We create two float64s to hold the numbers the user has entered and then use Go’s fmt.Sscanf() function to parse the line. This function takes a string to parse, a format—in this case two whitespace-separated floating-point numbers—and one or more pointers to variables to populate. (The & address of operator is used to get a pointer to a value; see §4.1, → 138.) The function returns the number of items it successfully parsed and an error (or nil). In the case of an error, we print an error message to os.Stderr—this is to make the error message visible on the console even if the program’s os.Stdout is redirected to a file. Go’s powerful and flexible scan functions are shown in use in Chapter 8 (§, → 378), and listed in Table 8.2 (→ 381).

If valid numbers were input and sent to the questions channel (in a polarstruct), we block the main goroutine waiting for a response on the answers channel. The additional goroutine created in the createSolver() function is itself blocked waiting for a polar on the questions channel, so when we send the polar, the additional goroutine performs the computation, sends the resultant cartesian to the answers channel, and then waits (blocking only itself) for another question to arrive. Once the cartesian answer is received in the interact() function on the answers channel, interact() is no longer blocked. At this point we print the result string using the fmt.Printf() function, and passing the polar and cartesian values as the arguments that the result string’s % placeholders are expecting. The relationship between the goroutines and the channels is illustrated in Figure 1.1.

Figure 1.1 Two communicating goroutines

The interact() function’s for loop is an infinite loop, so as soon as a result is printed the user is once again asked to enter a radius and angle, with the loop being broken out of only if the readerreads end of file—either interactively from the user or because the end of a redirected input file has been reached.

The calculations in polar2cartesian are very lightweight, so there was no real need to do them in a separate goroutine. However, a similar program that needed to do multiple independent heavyweight calculations as the result of each input might well benefit from using the approach shown here, for example, with one goroutine per calculation. We will see more realistic use cases for channels and goroutines in Chapter 7.

We have now completed our overview of the Go language as illustrated by the five example programs reviewed in this chapter. Naturally, Go has much more to offer than there has been space to show here, as we will see in the subsequent chapters, each of which focuses on a specific aspect of the language and any relevant packages from the standard library. This chapter concludes with a small exercise, which despite its size, requires some thought and care.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020