zzz6519003 / blog

My blog about coding
4 stars 1 forks source link

Book note #137

Open zzz6519003 opened 4 years ago

zzz6519003 commented 4 years ago

concurrency is about two or more separate activi- ties happening at the same time.

There are two main reasons to use concurrency in an application: separation of con- cerns and performance.

Separation of concerns is almost always a good idea when writing software; by group- ing related bits of code together and keeping unrelated bits of code apart, you can make your programs easier to understand and test, and thus less likely to contain bugs.

There are two ways to use concurrency for performance. The first, and most obvi- ous, is to divide a single task into parts and run each in parallel, thus reducing the total runtime. This is task parallelism. Although this sounds straightforward, it can be quite a complex process, because there may be many dependencies between the vari- ous parts. The divisions may be either in terms of processing—one thread performs one part of the algorithm while another thread performs a different part—or in terms of data—each thread performs the same operation on different parts of the data. This latter approach is called data parallelism.

The second way to use concurrency for performance is to use the available paral- lelism to solve bigger problems; rather than processing one file at a time, process 2 or 10 or 20, as appropriate.

zzz6519003 commented 4 years ago

Launching a thread


class background_task
{
public:
    void operator()() const
    {
        do_something();
        do_something_else();
    }
};
background_task f;
std::thread my_thread(f);