C++11 多线程编程《C++ Concurrency in Action》读书笔记(1)-Hello World of Concurrency in C++

1.1    Whatis concurrency?

Historically, most computers have had one processor, with a singleprocessing unit or  core, so they canreally only perform one task at a time. However it can switch between tasks manytimes per second. By doing a bit of one task and then a bit of another and soon,it appears that the tasks are happening concurrently. This is called task switching.We still talk about concurrencywith such systems. because the task switches are sofast,you can’t tell at which point a task may be suspended as the processorswitches to another one. The task switching provides an illusion of concurrencyto both the user and the applications themselves. Because there is only an illusionof concurrency,the behavior of applications may be subtly different when executing in asingle-processor task-switching environment compared to when executing in anenvironment with true concurrency.

Whether they have multiple processors or multiple cores within aprocessor (or both), these computers are capable of genuinely running more thanone task in parallel. We call this hardware concurrency.

Though the availability of concurrency in the hardware is most obviouswith multiprocessor or multicore systems, some processors can execute multiplethreads on a single core. The important factor to consider is really the number of hardware threads:the measure of how manyindependent tasks the hardware can genuinely run concurrently. Even with asystem that has genuine hardware concurrency, it’s easy to have more tasks thanthe hardware can run in parallel, so task switching is still used in these cases.

CONCURRENCY WITHMULTIPLE PROCESSES

The first way to make use of concurrency within an application is todivide the application into multiple,separate,single-threaded processes that are run at the same time. Theseseparate processes can then pass messages to each other through all the normalinterprocess communication channels (signals, sockets, files,pipes, and so on).两个缺点:进程间的通信较慢,因为操作系统一般会在进程间提供很多保护以避免一个进程无意间修改了另外一个进程的数据;由于操作系统必须分配内核资源给进程,因此启动进程的时间较长。

优点也有两个:the added protection operating systems typicallyprovide  between processes  and  the higher-level  communication  mechanisms mean that it can be easier to write safe concurrentcode with processes rather than threads. Usingseparate processes for concurrency also has an additional advantage—you can runthe separate processes on distinct machines connectedover a network. Though this increases  the communication  cost,  on a  carefully  designed system  it  can be  a  costeffective way of increasing the availableparallelism and improving performance.

CONCURRENCY WITHMULTIPLE THREADS

Threads are much like lightweight processes: each thread runsindependently of the others, and each thread may run a different sequence ofinstructions. But all threads in a process share the sameaddress space, and most of the data can be accessed directly from all threads—global variables remainglobal, and pointers or references to objects or data can be passed aroundamong threads.Although it’s often possible to share memory among processes,this is complicated to set up and often hard to manage, because memoryaddresses of the same data aren’t necessarily the same in different processes.

The shared address space and lack of protection of data between threadsmakes the overhead associated with usingmultiple threads much smaller than that fromusing  multiple processes, because theoperating system has less bookkeeping to do.But the flexibility of sharedmemory also comes with a price: if data is accessed by multiple threads, theapplication programmer must ensure that the view of data seen by each thread isconsistent whenever it is accessed.

The low overhead associated with launching and communicating betweenmultiple threads within a process compared to launching and communicatingbetween multiple single-threaded processes means that this is the favoured approachto concurrency in mainstream languages including C++, despite the potentialproblems arising from the shared memory. In addition, the C++ Standard doesn’t provideany intrinsic support for communication between processes, so applications thatuse multiple processes will have to rely on platform-specific APIs to do so.

1.2     Why use concurrency?

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

Usingconcurrency for separation of concerns: Usingthreads in this way generally makes the logic in each thread much simpler, becausethe interactions between them can be limited to clearly identifiable points,rather than having to intersperse the logic of the different tasks. In this case, the number of threads is independent of the number of CPU coresavailable, because the division into threads is based on the conceptual designrather than an attempt to increase throughput.

Usingconcurrency for performance: There aretwo ways to use concurrency for performance. The first, and most obvious, is todivide a single task into parts and run each in parallel, thus reducing the totalruntime.It’s frequently called embarrassinglyparallel. Embarrassingly parallel algorithms have goodscalability properties—as the number of available hardware threads goes up, theparallelism in the algorithm can be increased to match.

The second way to use concurrency for performance is to use theavailable parallelism to solve bigger problems; rather than processing one fileat a time, process 2 or 10 or 20, as appropriate.

1.3     When notto use concurrency

It’s just as important to know when notto use concurrency as it is toknow whento use it. Fundamentally, the only reason not to use concurrency iswhen the benefit is not worth  the cost. 

  • Code  using  concurrency  is  harder  to  understand  in  many  cases
  • The performance gain might not be as large as expected, there’s an inherent overhead associated with launching a thread, because the OShas to allocate the associated kernel resources and stack space and then add the new thread to the scheduler,all of which takes time.
  • Threads are a limited resource
  • The more threads you have running, the more context switching the operating system has to do

1.4     Concurrencyand multithreading in C++

Standardized support for concurrency through multithreading is a newthing for C++.It’s only with the upcoming C++11 Standard that you’ll be able towrite multithreaded code without resorting to platform-specific extensions.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值