Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying C++ System Programming Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
C++ System Programming Cookbook

C++ System Programming Cookbook

By : Onorato Vaticone
3.8 (4)
close
close
C++ System Programming Cookbook

C++ System Programming Cookbook

3.8 (4)
By: Onorato Vaticone

Overview of this book

C++ is the preferred language for system programming due to its efficient low-level computation, data abstraction, and object-oriented features. System programming is about designing and writing computer programs that interact closely with the underlying operating system and allow computer hardware to interface with the programmer and the user. The C++ System Programming Cookbook will serve as a reference for developers who want to have ready-to-use solutions for the essential aspects of system programming using the latest C++ standards wherever possible. This C++ book starts out by giving you an overview of system programming and refreshing your C++ knowledge. Moving ahead, you will learn how to deal with threads and processes, before going on to discover recipes for how to manage memory. The concluding chapters will then help you understand how processes communicate and how to interact with the console (console I/O). Finally, you will learn how to deal with time interfaces, signals, and CPU scheduling. By the end of the book, you will become adept at developing robust systems applications using C++.
Table of Contents (13 chapters)
close
close

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.

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
C++ System Programming Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon