Use and necessity of pthread_attr_init() - unix

I just created one c program to create threads using POSIX thread library functions.I didn't use pthread_attr_init() function in that. Even my program works fine.So, what is the use of pthread_attr_init() and what does it do...? I am not familiar in thread concepts.Can anyone tell me is it compulsory to use pthread_attr_init() in thread concept program..?

pthread_attr_init is used to initialise a thread attributes structure, which can then be passed to pthread_create.
If you are creating threads with default attributes, you pass a NULL pointer for the thread attributes argument to pthread_init and there is no need to initialise an attribute structure.
However, if you want to configure specific thread attributes, such as scheduling policy, priority, concurrency level, then you must use pthread_attr_init to initialise the attribute structure before manipulating it using the attribute accessors functions (pthread_set... and pthread_get...) and passing it to the pthread_init function.

Related

Rcpp-Modules: Understanding .finalizer() and why it doesn't get called

I have written a Rcpp-Module named RMaxima that spawns a child process when it's constructor is called. My motivation for this question is, that I need an object of this class to be destructed, when R exits a functions execution environment in which it has been allocated and bound to a name.
Here are the important parts of my source file:
class RMaxima
{
public:
RMaxima()
{
...
// spawnes child process by instantiating an object
myMaxima = new Maxima(...);
}
~RMaxima()
{
// causes the child process to terminate properly
delete myMaxima;
}
...
private:
Maxima* myMaxima;
};
static void rmaxima_finalizer(RMaxima* ptr)
{
if (ptr)
{
delete ptr;
}
}
RCPP_MODULE(Maxima)
{
class_<RMaxima>("RMaxima")
.constructor()
.method(...)
.finalizer(&rmaxima_finalizer)
;
}
My understanding of garbage collection in R is that when the interpreter exits an environment the value bindings from this environment are thrown away and R's garbage collection frees up memory for any unbound values.
However, this seems to be different for Rcpp-Modules: If I call and exit a function that creates an instance of my class
foo <- function() {
m <- new(Rmaxima)
...
}
then, as expected, m does not appear in the global environment. However, the child process is still running. This means that my class' destructor/ finalizer has not been called. It is called however, when I quit the R session or when I install my corresponding custom package during which loading is tested.
Why? How can I cause it being destructed in a different scope? "Extending R" (Chambers, 2016) gave me some hint
The Rcpp templated type allows conversions to and from "externalptr"
with computations in the C++ code specialized to the type T of the object referred
to. Templated code can in fact use 3 parameters: type, storage scope and a final-
izer to be called when the object pointed to is deleted. The object returned to R
is in all cases of class and type "externalptr". No information is available about
the parametrized form.
as to point out that classes are returned as externalptr and protected from gc(), but I don't see the connection, since object is typeof(m): S4, i.e. a reference class.
Any further hint, where to read about this?
You are using Rcpp Modules which are in a way an alternative to using things yourself with an external pointer. Rcpp offers you Rcpp::XPtr and those are used by a few packages you could look at. (My favourite is a quick GitHub search as in this one across the 'cran' org that mirrors CRAN -- it shows over 1k code hits so some further triage needed.)
And XPtr itself seems to have an open issue in as far as guaranteed access to the finalizer is concerned; I filed issue #1108 on that last year and plan to revisit this 'soon'. But despite that issue which may be a corner case, in general this appears to work. So I would look into XPtr and/or the two helper packages for XPtr use on CRAN.
Lastly, Rcpp Classes were an extension written and contributed by John. They have not seen too much use though. Rcpp Modules is fairly widely used, and there too you could look at examples.
Lastly, you could also do something more simple and direct:
create a class Foo with an empty-ish constructor
have static pointer to a singleton of the class
create an init method to set up the class and have it hold the memory it needs
have setter/getter/worker/result methods as needed
create a teardown method to free the memory
and then call init first (maybe from package load), followed by all the work and then ensure the teardown is called. It's a far-from-perfect design (maybe teardown is not called?) but the simplicity gives you a comparison. And once you have the fragments you can build fancier structures on top.

typescript, ts-morph module, is there access to underlying `ts.SourceFile` instance from a `ts-morph.SourceFile` instance?

I am trying out the ts-morph npm module to replace some code which I have already written but which overlaps ts-morph and is inferior. Nevertheless, I have some existing functions that take an ts.Node type arguments, mostly for exploration and discovery, which I need to use for reference while trying out ts-morph.
However, I can't see a way to access the underlying ts.Node instance from a ts-morph.SourceFile instance - there are no ts-morph functions with return type of ts.Node or ts.TypeChecker.
This doesn't work
(sourceFile as unknown) as ts.SourceFile,
(checker as unknown) as ts.TypeChecker,
because, for starters, (sourceFile as unknown) as ts.SourceFile doesn't have a kind member.
Is there a way access the underlying ts.Node instance from, e.g., ts-morph.SourceFile?
ts-morph provides access to all the underlying compiler API objects it wraps.
For any node, you can access the underlying compiler node using the compilerNode property:
sourceFile.compilerNode // ts.SourceFile
Note though that the underlying compiler node will become out of date whenever the source file is manipulated via ts-morph (ex. you add a class to the source file, remove a function, or other stuff like that).
https://github.com/dsherret/ts-morph/blob/af35677f3b498ed0f8e87e4b6c92a7246cfab210/packages/ts-morph/lib/ts-morph.d.ts#L3189
To get the TypeScript TypeChecker, use the compilerObject property on TypeChecker:
project.getTypeChecker().compilerObject // ts.TypeChecker

Why recommend use ctx as the first parameter?

As the documentation said
Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx
but I found, in the typical http request handle function, a http.Request object has .Context() method can retrieve the context which http request associate with.
So why recommend to use context as the first parameter in these functions? Is that reasonable in this situation?
I know that is not an absolute rule. But I want to know why the HandlerFunc is func(ResponseWriter, *Request) instead of func(context.Context, ResponseWriter, *Request).
Apparently HandlerFunc breaks this recommendation.
As described in the documentation you quoted above, ctx should be a (very) common argument for many functions. This is similar to the way many functions return an error. The best place for a common argument/return value is either as the first, or last in a list. (Arguably, Go could have chosen to make error always be the first return value--I won't discuss that here).
Since variadic variables may only be the last in the list of function arguments, this leaves the only option for a common argument to be the first one.
I expect this is why ctx is always first.
This pattern is often seen with other variables in Go (and other languages) as well. Any time a common variable is used by a set of related functions, that common variable often comes first in the argument list (or possibly second, after ctx).
Contrary to the advice you quoted, there are libraries that store ctx in a struct, rather than passing it around as the first argument. These are usually (always?) libraries which had to be retro-fitted to use ctx, long after the library contract was set in stone (by the Go 1.x compatibility guarantee).
Generally, you should follow the advice to pass ctx as the first argument, for any new work.

How to mock an inlined InitiatingFlow return value during another flow

I have SomeBigFlow that calls multiple subflows inside it i.e ValidateFlowA, ValidateFlowB. Assuming it is mandatory for A and B to be initiating flows not functions.
How do I mock a return value for ValidateFlowA when I run the SomeBigFlow in Junit?
I've seen some references to using registerAnswer to mock flows' return value here. I am also curious why this function is only available for InternalMockNetwork.MockNode but not MockNetwork.StartedMockNode which is typically used during junit testing)
I thought I could replicate it by having node[1].registerAnswer(ValidateFlowA.class, 20). But when I ran node[1].startFlow(SomeBigFlow).resultFuture.getOrThrow(), the ValidateFlowA is still using its default call implementation instead of returning the mocked 20 integer value. Maybe I'm using it wrong.
Any pointers on how to make this work or is there a solution to achieve mocking inlined subflows returned values? The only other way I can think of is have a rule of thumb that whenever calling an inlined subflow, put them in an open fun that can be overridden during mocknetwork testing - this makes inlined subflow tedious, hoping for a neater way.
For now, you'd have to use a similar approach to the one outlined here: Corda with mockito_kotlin for unit test.
In summary:
Make the FlowLogic class you are testing open, and move the call to the subflow into an open method
For testing, create a subclass of the open FlowLogic class where you override the open method to return a dummy result
Use this subclass in testing

Kotlin: How are a Delegate's get- and setValue Methods accessed?

I've been wondering how delegated properties ("by"-Keyword) work under-the-hood. I get that by contract the delegate (right side of "by") has to implement a get and setValue(...) method, but how can that be ensured by the compiler and how can those methods be accessed at runtime? My initial thought was that obviously the delegates must me implementing some sort of "SuperDelegate"-Interface, but it appears that is not the case. So the only option left (that I am aware of) would be to use Reflection to access those methods, possibly implemented at a low level inside the language itself. I find that to be somewhat weird, since by my understanding that would be rather inefficient. Also the Reflection API is not even part of the stdlib, which makes it even weirder.
I am assuming that the latter is already (part of) the answer. So let me furthermore ask you the following: Why is there no SuperDelegate-Interface that declare the getter and setter methods that we are forced to use anyway? Wouldn't that be much cleaner?
The following is not essential to the question
The described Interface(s) are even already defined in ReadOnlyProperty and ReadWriteProperty. To decide which one to use could then be made dependable on whether we have a val/var. Or even omit that since calling the setValue Method on val's is being prevented by the compiler and only use the ReadWriteProperty-Interface as the SuperDelegate.
Arguably when requiring a delegate to implement a certain interface the construct would be less flexible. Though that would be assuming that the Class used as a Delegate is possibly unaware of being used as such, which I find to be unlikely given the specific requirements for the necessary methods. And if you still insist, here's a crazy thought: Why not even go as far as to make that class implement the required interface via Extension (I'm aware that's not possible as of now, but heck, why not? Probably there's a good 'why not', please let me know as a side-note).
The delegates convention (getValue + setValue) is implemented at the compiler side and basically none of its resolution logic is executed at runtime: the calls to the corresponding methods of a delegate object are placed directly in the generated bytecode.
Let's take a look at the bytecode generated for a class with a delegated property (you can do that with the bytecode viewing tool built into IntelliJ IDEA):
class C {
val x by lazy { 123 }
}
We can find the following in the generated bytecode:
This is the field of the class C that stores the reference to the delegate object:
// access flags 0x12
private final Lkotlin/Lazy; x$delegate
This is the part of the constructor (<init>) that initialized the delegate field, passing the function to the Lazy constructor:
ALOAD 0
GETSTATIC C$x$2.INSTANCE : LC$x$2;
CHECKCAST kotlin/jvm/functions/Function0
INVOKESTATIC kotlin/LazyKt.lazy (Lkotlin/jvm/functions/Function0;)Lkotlin/Lazy;
PUTFIELD C.x$delegate : Lkotlin/Lazy;
And this is the code of getX():
L0
ALOAD 0
GETFIELD C.x$delegate : Lkotlin/Lazy;
ASTORE 1
ALOAD 0
ASTORE 2
GETSTATIC C.$$delegatedProperties : [Lkotlin/reflect/KProperty;
ICONST_0
AALOAD
ASTORE 3
L1
ALOAD 1
INVOKEINTERFACE kotlin/Lazy.getValue ()Ljava/lang/Object;
L2
CHECKCAST java/lang/Number
INVOKEVIRTUAL java/lang/Number.intValue ()I
IRETURN
You can see the call to the getValue method of Lazy that is placed directly in the bytecode. In fact, the compiler resolves the method with the correct signature for the delegate convention and generates the getter that calls that method.
This convention is not the only one implemented at the compiler side: there are also iterator, compareTo, invoke and the other operators that can be overloaded -- all of them are similar, but the code generation logic for them is simpler than that of delegates.
Note, however, that none of them requires an interface to be implemented: the compareTo operator can be defined for a type not implementing Comparable<T>, and iterator() does not require the type to be an implementation of Iterable<T>, they are anyway resolved at compile-time.
While the interfaces approach could be cleaner than the operators convention, it would allow less flexibility: for example, extension functions could not be used because they cannot be compiled into methods overriding those of an interface.
If you look at the generated Kotlin bytecode, you'll see that a private field is created in the class holding the delegate you're using, and the get and set method for the property just call the corresponding method on that delegate field.
As the class of the delegate is known at compile time, no reflection has to happen, just simple method calls.

Resources