Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
C++ System Programming Cookbook

You're reading from   C++ System Programming Cookbook Practical recipes for Linux system-level programming using the latest C++ features

Arrow left icon
Product type Paperback
Published in Feb 2020
Publisher Packt
ISBN-13 9781838646554
Length 292 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Onorato Vaticone Onorato Vaticone
Author Profile Icon Onorato Vaticone
Onorato Vaticone
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Getting Started with System Programming 2. Revisiting C++ FREE CHAPTER 3. Dealing with Processes and Threads 4. Deep Dive into Memory Management 5. Using Mutexes, Semaphores, and Condition Variables 6. Pipes, First-In First-Out (FIFO), Message Queues, and Shared Memory 7. Network Programming 8. Dealing with Console I/O and Files 9. Dealing with Time Interfaces 10. Managing Signals 11. Scheduling 12. Other Books You May Enjoy

Understanding concurrency

In the past, it was common for a C++ developer to write programs by using threading libraries or native threading mechanisms (for example pthread, a Windows thread). Since C++11, this has changed drastically and concurrency is another big feature that was added that goes in the direction of a self-consistent language. The two new features we'll look at in this recipe are std::thread and std::async.

How to do it...

In this section, we'll learn how to use std::thread with a basic scenario (create and join) and how to pass and receive parameters to it:

  1. std::thread: By using the basic thread methods, create and join, write the following code:
#include <iostream>
#include <thread>
void threadFunction1 ();
int main()
{
std::thread t1 {threadFunction1};
t1.join();
return 0;
}
void threadFunction1 ()
{
std::cout << "starting thread 1 ... " << std::endl;
std::cout << "end thread 1 ... " << std::endl;
}
  1. Compile it with g++ concurrency_01.cpp -lpthread.

The second example is similar to the previous one but in this case, we pass and get parameters:

  1. std::thread: Create and join a thread, passing a parameter and getting a result. Write the following code:
#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
void threadFunction (std::vector<int> &speeds, int& res);
int main()
{
std::vector<int> speeds = {1, 2, 3, 4, 5};
int result = 0;
std::thread t1 (threadFunction, std::ref(speeds),
std::ref(result));
t1.join();
std::cout << "Result = " << result << std::endl;
return 0;
}
void threadFunction (std::vector<int> &speeds, int& res)
{
std::cout << "starting thread 1 ... " << std::endl;
for_each(begin(speeds), end(speeds), [](int speed)
{
std::cout << "speed is " << speed << std::endl;
});
res = 10;
std::cout << "end thread 1 ... " << std::endl;
}
  1. Compile it using g++ concurrency_02.cpp -lpthread.

The third example uses async to create a task, execute it, and get the result, as follows:

  1. std::async: Here, we can see why async is called task-based threading. Write the following code:
root@b6e74d5cf049:/Chapter2# cat concurrency_03.cpp
#include <iostream>
#include <future>
int asyncFunction ();
int main()
{
std::future<int> fut = std::async(asyncFunction);
std::cout << "max = " << fut.get() << std::endl;
return 0;
}
int asyncFunction()
{
std::cout << "starting asyncFunction ... " << std::endl;
int max = 0;
for (int i = 0; i < 100000; ++i)
{
max += i;
}
std::cout << " Finished asyncFunction ..." << std::endl;
return max;
}
  1. Now, we need to compile the program. There is a catch here. Since we're using a threading mechanism, the compilers rely on the native implementations, which in our case turn out to be pthread. In order to compile and link without errors (we'd get an undefined reference), we need to include -lpthread:
g++ concurrency_03.cpp -lpthread

In the fourth example, std::async used in conjunction with std::promise and std::future is a good and easy way of making two tasks communicate with each other. Let's take a look:

  1. std::async: This is another std::async example showing a basic communication mechanism. Let's code it:
#include <iostream>
#include <future>
void asyncProducer(std::promise<int> &prom);
void asyncConsumer(std::future<int> &fut);
int main()
{
std::promise<int> prom;
std::future<int> fut = prom.get_future();
std::async(asyncProducer, std::ref(prom));
std::async(asyncConsumer, std::ref(fut));
std::cout << "Async Producer-Consumer ended!" << std::endl;
return 0;
}
void asyncConsumer(std::future<int> &fut)
{
std::cout << "Got " << fut.get() << " from the producer ... "
<< std::endl;
}
void asyncProducer(std::promise<int> &prom)
{
std::cout << " sending 5 to the consumer ... " << std::endl;
prom.set_value (5);
}
  1. And finally, compile it: g++ concurrency_04.cpp -lpthread

How it works...

Let's analyze the previous four programs:

  1. std::thread: The following program shows basic thread usage for create and join:

There's nothing really complex in this first test. std::thread was initialized with a function through the uniform initialization and joined (waiting for the thread to be completed). The thread would accept a function object:

struct threadFunction 
{
int speed;
void operator ()();
}
std::thread t(threadFunction);
  1. std::thread: Create and join a thread, passing a parameter and getting a result:

This second test shows how to pass a parameter using std::vector<int>& speeds to the thread and get the return parameter, int& ret. This test shows how to pass parameters to a thread, and is not multithreaded code (that is, passing the same parameters to other threads will result in a race condition if at least one thread will be writing on them)!

  1. std::async: Here, we can see why async is called task-based threading:

Note that when we call std::async(asyncFunction);, we could use auto fut = std::async(asyncFunction); to deduce the type of the return from std::async at compile time.

  1. std::async: This is another std::async example showing a basic communication mechanism:

The consumer, void asyncConsumer(std::future<int> &fut), calls the get() method on the future to get the value set by the producer through the set_value() method on the promise. fut.get() waits for the value to be computed, if necessary (that is, it's a blocking call).

There's more...

The C++ concurrent library doesn't just include the features shown in this recipe, although these are the foundational ones. You are invited to explore the full set of concurrency tools that are available by going to Chapter 5, paragraph three of The C++ Programming Language by Bjarne Stroustrup.

See also

The books Effective Modern C++ by Scott Meyers and The C++ Programming Language by Bjarne Stroustrup cover these topics in great detail.

You have been reading a chapter from
C++ System Programming Cookbook
Published in: Feb 2020
Publisher: Packt
ISBN-13: 9781838646554
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime