Is it possible to use GCD without blocks? Is there a way to use GCD using _f variant as mikeash says in his post. I searched around and there is no proof for either sides. is it possible or impossible.
If its doable please give an example.
/Selvin
Of course it is possible! By _f variants Mike just mean set of GCD functions with _f suffix. They are alternatives for usual GCD functions but can accept a user defined function as a parameter instead of blocks. There are plenty of them:
dispatch_async_f
dispatch_sync_f
dispatch_after_f
dispatch_apply_f
dispatch_group_async_f
dispatch_group_notify_f
dispatch_set_finalizer_f
dispatch_barrier_async_f
dispatch_barrier_sync_f
dispatch_source_set_registration_handler_f
dispatch_source_set_cancel_handler_f
dispatch_source_set_event_handler_f
They accept dispatch_function_t parameter (instead of usual dispatch_block_t) which is defined as follows:
typedef void (*dispatch_function_t)(void*). As you see it can accept any user parameter and also a function because of *void pointer. So you can even use dispatch_function_t with function that have no arguments - you can just write a wrapper function like so:
void func(void) {
//do any calculations you want here
}
void wrapper_function(void*) { func(); }
dispatch_async_f(queue, 0, &wrapper_function);
Or pass a function pointer as a parameter. Or on the contrary you can use _f variants of GCD functions with user defined functions which can accept any number of arguments via the varargs (variadic functions) - just write a function wrapper for it also as above. As you see _f functions is rather a powerful mechanism and you are not limited only with blocks without parameters for GCD but can use usual functions.
Yes you can, as stated on the article:
You can use GCD without blocks, via the _f variants provided for every
GCD function that takes a block
If you look at the GCD documentation you can check the variants. If you need a quick example there are many on SO:
Related
Lets say you have a complex Lua application, and there is some base function that different parts of your code call repeatedly. It's a stateless function with little to no side effects, and fairly simple.
How does the virtual machine handle this? Does it queue up all the calls, and let them run one by one, waiting for the function to to return before calling it again? Or does it do some trickery to avoid this sort of situation? What if the function had some big side effects, like print()?
Lua is single threaded so every function call must return before the next one is called. If a function is blocked then so is the VM. The only way around that is coroutines or Lua lanes or C threads.
I understand closures, even though I scarcely use them, but whenever I can squeeze one I have no idea of how to name it.
The best I can think of is sticking a "make" before what would be the name of the function:
function makeSortSelection(settings1, settings2) {
return function() {
/* sort stuff attending to settings1 and settings2 */
};
}
$("#sort-button").click(makeSortSelection('ascending',foo));
(I almost always use them in Javascript, but I guess this is a very language-agnostic question)
Sadly, most examples I found of closures just use "foo" or "sayHello". I like to give all my functions a verb as name: functions "do stuff", and their name reflects it ("sortSelection", "populateForm"). In the same spirit, how should I name closures, that "do things that do stuff"? What conventions do you use, and what are the most common?
PD: I tend to use Google's style guide when in doubt, but it says nothing about this.
Closures aren't nameable entities. Functions are nameable but a closure isn't a function.
Rather than define "a closure" it is easier to define the circumstances under which closure arises.
A (lexical) closure (in javascript) occurs and continues to exist as long a persistent external reference to an inner function exists, but neither the outer function nor the inner function nor the reference to the inner function is, in itself, a closure. Pragmatically speaking, a closure is a construct comprising all these elements plus a feature of the language by which garbage collection is suppressed when they exist.
In my opinion it is wrong, as some claim, that "all functions are closures". Yes, all functions have a scope chain, but a closure should only be regarded as existing once an outer function has completed and returned, and a persistent reference to an inner function exists.
By all means give the returned function a verb-based name, just like any other named function - there's no need to regard it differently just because it is was returned by another function. In every respect the returned function is just a function - it just happens to be a function with access to the scope chain of the (execution context of the) outer function that brought it into being - nothing more than that.
EDIT:
I just realised I didn't address the critical point of the question - rephrased "how to name a function that exists for the express purpose of forming a closure by returning a function".
Like you, I have a problem here.
Most often I use the "make" prefix, as in your example. This seems to be best most of the time.
I have also used "_closure" as a suffix, This doesn't obey the "verb rule" but has the advantage of being independent of natural language. "Make" is strictly an English word and speakers of other languages will probably choose to use their own "faire", "machen" etc. On the other hand, "closure" is universal - it remains, as far as I'm aware, untranslated in other languages. Therefore, "closure" as a suffix (or prefix) could be better in scripts that are likely to be used/modded on a world-wide basis.
I'm going over some older Dart code, addressing breaking changes with the latest Dart SDK. This one I can't figure out:
Future<DateTime> get lastsave =>
client.lastsave.transform((int unixTs) =>
new DateTime.fromMillisecondsSinceEpoch(unixTs * 1000, isUtc:true));
=>
The method 'transform' is not defined for the class 'Future<List<int>>'
From what I understand, the purpose of Future.transform() was to apply a synchronous transformation (see e.g. this discussion thread). I.e. convert the async call to a sync call and return the value.
Has Future.transform been replaced with something else?
Must have been quite a while since that code was updated ;)
Just replace transform with then and it should work.
From https://groups.google.com/a/dartlang.org/forum/#!topic/misc/Boch2XH9Tmk
We have also improved the Future class, and made it simpler to use. One simple “then” methods lets you apply asynchronous or synchronous functions to the result of a future, merging the three methods “chain”, “transform” and “then”. Streams and Futures should make asynchronous Dart programs easier to write and read, and should reduce some types of programming errors.
So, if I have a device (or global) function that creates/copies some data into shared memory and I later call another device function, like so:
__global__ void a(){
__shared__ int blah=0;
fun();
}
__device__ void fun(){
blah = 1; //perform some operations
//do whatever
}
I'm a bit rusty with my CUDA, I think you might have had to "redefine" shared variable (I assume the operation checked if a shared variable of that name exists, if so assigns it) - this had the effect of creating context - so basically the variable didn't just come out of nowhere. Alternatively, if it's similar to having a global variable in standard C/C++ and I can just reference it, like I did above, it'd be great.
I am familiar with memory hierarchy, I'm just rusty on the semantics of creating/referencing memory.
Please advise on whether the above sketch would work. Thanks.
No that won't work in CUDA, any more that it would work in standard C99. Currently, the preferred method of __device__ function compilation is inline expansion (they are also compiled as standalone code objects for the Fermi architecture), but even so __device__ functions still must obey standard syntax and scope conventions of C99. So you need to pass arguments which don't have compilation unit scope by reference to __device__ functions.
I'm trying to implement a pattern I read from Don Syme's blog
(https://blogs.msdn.microsoft.com/dsyme/2010/01/09/async-and-parallel-design-patterns-in-f-parallelizing-cpu-and-io-computations/)
which suggests that there are opportunities for massive performance improvements from leveraging asynchronous I/O. I am currently trying to take a piece of code that "works" one way, using Array.Parallel.Map, and see if I can somehow achieve the same result using Async.Parallel, but I really don't understand Async.Parallel, and cannot get anything to work.
I have a piece of code (simplified below to illustrate the point) that successfully retrieves an array of data for one cusip. (A price series, for example)
let getStockData cusip =
let D = DataProvider()
let arr = D.GetPriceSeries(cusip)
return arr
let data = Array.Parallel.map (fun x -> getStockData x) stockCusips
So this approach contructs an array of arrays, by making a connection over the internet to my data vendor for each stock (which could be as many as 3000) and returns me an array of arrays (1 per stock, with a price series for each one). I admittedly don't understand what goes on underneath Array.Parallel.map, but am wondering if this is a scenario where there are resources wasted under the hood, and it actually could be faster using asynchronous I/O? So to test this out, I have attempted to make this function using asyncs, and I think that the function below follows the pattern in Don Syme's article using the URLs, but it won't compile with "let!".
let getStockDataAsync cusip =
async { let D = DataProvider()
let! arr = D.GetData(cusip)
return arr
}
The error I get is:
This expression was expected to have type Async<'a> but here has type obj
It compiles fine with "let" instead of "let!", but I had thought the whole point was that you need the exclamation point in order for the command to run without blocking a thread.
So the first question really is, what's wrong with my syntax above, in getStockDataAsync, and then at a higher level, can anyone offer some additional insight about asychronous I/O and whether the scenario I have presented would benefit from it, making it potentially much, much faster than Array.Parallel.map? Thanks so much.
F# asynchronous workflows allow you to implement asynchronous computations, however, F# makes a distinction between usual computation and asynchronous computations. This difference is tracked by the type-system. For example a method that downloads web page and is synchronous has a type string -> string (taking URL and returning HTML), but a method that does the same thing asynchronously has a type string -> Async<string>. In the async block, you can use let! to call asynchronous operations, but all other (standard synchronous) methods have to be called using let. Now, the problem with your example is that the GetData operation is ordinary synchronous method, so you cannot invoke it with let!.
In the typical F# scenario, if you want to make the GetData member asynchronous, you'll need to implement it using an asynchronous workflow, so you'll also need to wrap it in the async block. At some point, you will reach a location where you really need to run some primitive operation asynchronously (for example, downloading data from a web site). F# provides several primitive asynchronous operations that you can call from async block using let! such as AsyncGetResponse (which is an asynchronous version of GetResponse method). So, in your GetData method, you'll for example write something like this:
let GetData (url:string) = async {
let req = WebRequest.Create(url)
let! rsp = req.AsyncGetResponse()
use stream = rsp.GetResponseStream()
use reader = new System.IO.StreamReader(stream)
let html = reader.AsyncReadToEnd()
return CalculateResult(html) }
The summary is that you need to identify some primitive asynchronous operations (such as waiting for the web server or for the file system), use primitive asynchronous operations at that point and wrap all the code that uses these operations in async blocks. If there are no primitive operations that could be run asynchronously, then your code is CPU-bound and you can just use Parallel.map.
I hope this helps you understand how F# asynchronous workflows work. For more information, you can for example take a look at Don Syme's blog post, series about asynchronous programming by Robert Pickering, or my F# web cast.
#Tomas already has a great answer. I'll just say a couple bits in addition.
The idiom for F# asyncs is to name the method with an "Async" prefix (AsyncFoo, not FooAsync; the latter is an idiom already used by another .NET technology). So your functions should be getStockData and asyncGetStockData.
Inside an async workflow, whenever you use let! instead of let or do! instead of do, the thing on the right should have type Async<T> instead of T. Basically you need an existing async computation in order to 'go async' at this point in the workflow. Each Async<T> will itself be either some other async{...} workflow, or else an async "primitive". The primitives are defined in the F# library or created in user code via Async.FromBeginEnd or Async.FromContinuations which enable defining the low-level details of starting a computation, registering an I/O callback, releasing the thread, and then restarting the computation when getting called back. So you have to 'plumb' async all the way down to some truly-async-I/O-primitive in order to get the full benefits of async I/O.