Programming languages – why are closures suddenly useful for optimizing programs to run on multiple cores?

I read an article claiming that closure (or "block") is a useful weapon in "multi-nuclear war", because

Now, I'm not talking about the usefulness of closures, or concurrent programming in the shared memory model, but what's the difference between threads that only act on local data (or processes, or actors, or...)?

Isn't concurrent programming, as a thread without a scheduler, itself a closure?

What is closure with nonlocal side effects?

Solution

The point of contention is that using closures in a programming language makes it easier to do some work in another thread I think the author should mention the importance of higher-order functions in this argument

My favorite introduction to higher-order functions is "why functional programming matters". I won't try to show a bad copy here

Therefore, if you want to execute closures in a for loop, using closures will not provide parallelism for free, for example

for (int i = 0; i < numElements; i++) {
  result[i] = closure(inputs[i],i);
}

Because the language cannot determine whether closures (a, b) change the result or other values in the input array in some way However, languages with higher-order functions (such as map) specify that the function passed to map should not view or change other values in the input and prevent it from affecting other results Therefore, code like the following (common in functional languages) can parallelize for you without creating a worker thread pool and handing them closures:

results = map(closure,inputs,[0..numElements-1]);

In these languages, closures eliminate the pain of declaring new functions in short code This makes using higher - order functions more interesting

The following Haskell code defines a function f that accepts a list of numbers and returns a list, where each input I is replaced with 2I 1 The trouble of calculating 2I 1 by saving the creation function is 1 line of code instead of 2 lines

f nums = map (\i -> 2*i+1) nums

Again, see "why functional programming matters" for a strong argument on how to extend to the actual code base

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>