Behavior of PTHREAD_MUTEX_INITIALIZER on iOS - ios

Assuming there are a few classes, each using something like the following code to protect their area.
static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
[..]
pthread_mutex_lock(&_mutex);
//some code
pthread_mutex_unlock(&_mutex);
The question:
Do all these classes share the same mutex (so if s/o locks the mutex no one else will be able to access the protected area). Or does every PTHREAD_MUTEX_INITIALIZER create a new mutex?
Literature seems to be ambiguous about this topic, depending on the system PTHREADS is running on.

This has nothing to do with the PTHREAD_MUTEX_INITIALIZER (or even Pthreads) and cannot be system dependent.
This is a basic C++ language question. You're using a static variable so there is only one of it. You haven't shown enough code to know if it's a static member of a class (so there's one _mutex per class type, not per object) or a global static (so there's one _mutex per file).

Related

Google Dart visibility of methods and properties

Just to avoid some misunderstanding, I know that Google Dart handles things on a library level and that private properties and methods can be identified with a underscore prefix.
Is this still up to date as of 2017? Are there any plans for adding object level visibility keywords like: private, protected or public?
I dont just want to do something random but im rather interested in best practices. The way I see it is: if I dont want class one to see what class two has then both must be in different libraries, those libraries then are part of a bigger package.
libraries = privacy between classes
packages = privacy between files
What about fine grained control of privacy? I mean maybe there is 1 thing I want private. What about using visibility when using inheritance? I mean protected keywords can be really valuable.
Here a little example in one file:
class one {
int n = 1;
one() {
var test = new two(n);
print(test.showNumber());
}
}
class two {
int n = 2;
two(n) {
this.n += n;
}
int showNumber() {
return n;
}
}
As it stands now, both classes can do what they want.
Dart still has only library-level privacy.
Library-level privacy with identifiers starting with an underscore is also enforced at runtime.
The analyzer provides some additional features during static analysis which are ignored at runtime though.
Per convention also libraries inside lib/src are considered private, and should now be imported from other packages. The linter, a plugin for the analyzer notifies about violations. Seems to be part of the analyzer itself.
The meta package provides some annotations that are supported by the analyzer.
#protected produces a warning if public members are referenced by code from other libraries that is not within subclasses.
#visibleForTesting produces a warning if public members are references by code that is not within the test directory (of the same package I assume) Not sure if the analyzer actually warns about violations yet, otherwise it's planned to do that.
As far as I remember there are some issues for more rules but not yet implemented.
From #lrn's comment below
One reason for the current design is that Dart allows dynamic calls, even in strong mode. That means that o.foo() cannot be rejected based on "class level privacy" without retaining and checking extra information at runtime. With library/lexical based privacy, it's absolutely clear whether o.foo() or o._foo() is allowed (it always is, it's just that the latter can only refer to the _foo name of the same library). If Dart only had static resolution of identifiers, then it could use static information (like a private declaration) to reject at compile time without a runtime overhead.

Using hidden properties vs. private iVars

This question is specifically focused around static libraries / frameworks; in other words, code that other people will eventually touch.
I'm fairly well versed in properties, since I started iOS development when iOS 6 was released. I have used hidden properties declared in interface extensions to do all of my "private" property work, including using readonly on public facing properties I don't want others to modify and readwrite within interface extensions.
The important thing is that I do not want other people who are using these static libraries / frameworks to be accessing these properties if I don't allow it, nor writing these properties if I let them read it.
I've known for a while that they could theoretically create their own interface extension and make my readonly properties readwrite themselves, or guess the names of hidden properties.
If I want to prevent this, should I be using ivars with the #private tag with directly declared ivars? Are there potential downfalls to doing it this way? Does it actually get me an additional measure of security, or is it a red herring?
Under ARC the only mode supported by properties and not instance variables is copy - so if you need copy use a property.
If you declare your private instance variables in the #implementation section:
#implementation MyClass
{
// private instance vars
}
then it takes serious effort to access them from outside the class. As you say accessing a "private" property just takes guessing its name - or using the library calls which tell you.
Is it worth it for security? YMMV. But its a good coding practice regardless.
Addendum
As the comment trail shows there has been much discussion over my use of serious effort.
First let's be clear: Objective-C is in the C family of languages, they all allow the programmer to just about anything they choose while staying within the language[*] - these are not the languages of choice if you want strong typing, access restrictions, etc., etc. within your code.
Second, "effort" is not an absolute measure! So maybe I should have chosen the word "obvious" to qualify it rather than "serious". To access a private property just requires the use of a standard method call where the object has type id - there is little clue in the code that the method being called is hidden. To access a private variable requires either an API call (a runtime function or KVC call) or some pointer manipulation - the resultant code looks nothing like a standard variable assignment. So its more obvious.
That said, apart from uses requiring copy, under ARC there is no good reason to use a private property when a private instance variable will do. For a private variable fred compare:
self.fred = 42; // property access, may involve a call (if not optimised out)
_fred = 42; // common way to bypass the accessors and get at the underlying var
fred = 42; // direct access
Take your pick, there is no right answer, but there isn't a wrong one either - this is the realm of opinion (and that is of course an opinion ;-)). I would often pick the last one, private variable - clean & simple. However #RobNapier in his answer prefers the use of properties.
[*] Note: once you consider linking to external code, say written in assembler, all bets are of in any language. At that point you have to look at the "hardware" (real or virtual) and/or "OS" to provide protection.
You should use private ("hidden") properties here. There is no "security" risk. The "attacker" in this scenario is the caller. The caller has complete access to all memory in the process. She can access anything in your framework she wants and there is absolutely nothing you can do to stop that (nor should you). This is true in any language. You can bypass "private:" designations in C++ as well if you know what you're doing. It's all just memory at the end of the day.
It is not your job to protect yourself or your framework from the caller. You both have the same goal: correct program behavior. Your goal is to protect callers from themselves. Make it difficult for them to use your framework incorrectly and easy to use it correctly.
So, you should use the tool that leads to the most correct code. And that tool is properties, and avoiding directly ivar access except in init and dealloc.

A pragmatic view on private vs public

I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.
Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.
So, what's the whole point in these restrictions?
The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.
The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.
If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.
The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.
A small example, suppose we have:
class MyDate
{
public int y, m, d;
public void AdvanceDays(int n) { ... } // complicated month/year overflow
// other utility methods
};
You cannot prevent a user of the class to ignore AdvanceDays() and simply do:
date.d = date.d + 1; // next day
But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.
The whole point is to use private and protected to prevent exposing internal details of your class, so that other classes only have access to the public "interfaces" provided by your class. This can be worthwhile if done properly.
I agree that private can be a real pain, especially if you are extending classes from a library. Awhile back I had to extend various classes from the Piccolo.NET framework and it was refreshing that they had declared everything I needed as protected instead of private, so I was able to extend everything I needed without having to copy their code and/or modify the library. An important take-away lesson from that is if you are writing code for a library or other "re-usable" component, that you really should think twice before declaring anything private.
The keyword private shouldn't be used to privatize a property that you want to expose, but to protect the internal code of your class. I found them very helpful because they help you to define the portions of your code that must be hidden from those that can be accessible to everyone.
One example that comes to my mind is when you need to do some sort of adjustment or checking before setting/getting the value of a private member. Therefore you'd create a public setter/getter with some logic (check if something is null or any other calculations) instead of accessing the private variable directly and always having to handle that logic in your code. It helps with code contracts and what is expected.
Another example is helper functions. You might break down some of your bigger logic into smaller functions, but that doesn't mean you want to everyone to see and use these helper functions, you only want them to access your main API functions.
In other words, you want to hide some of the internals in your code from the interface.
See some videos on APIs, such as this Google talk.
Having recently had the extreme luxury of being able to design and implement an object system from scratch, I took the policy of forcing all variables to be (equivalent to) protected. My goal was to encourage users to always treat the variables as part of the implementation and not the specification. OTOH, I also left in hooks to allow code to break this restriction as there remain reasons to not follow it (e.g., the object serialization engine cannot follow the rules).
Note that my classes did not need to enforce security; the language had other mechanisms for that.
In my opinion the most important reason for use private members is hiding implementation, so that it can changed in the future without changing descendants.
Some languages - Smalltalk, for instance - don't have visibility modifiers at all.
In Smalltalk's case, all instance variables are always private and all methods are always public. A developer indicates that a method's "private" - something that might change, or a helper method that doesn't make much sense on its own - by putting the method in the "private" protocol.
Users of a class can then see that they should think twice about sending a message marked private to that class, but still have the freedom to make use of the method.
(Note: "properties" in Smalltalk are simply getter and setter methods.)
I personally rarely make use of protected members. I usually favor composition, the decorator pattern or the strategy pattern. There are very few cases in which I trust a subclass(ing programmer) to handle protected variables correctly. Sometimes I have protected methods to explicitly offer an interface specifically for subclasses, but these cases are actually rare.
Most of the time I have an absract base class with only public pure virtuals (talking C++ now), and implementing classes implement these. Sometimes they add some special initialization methods or other specific features, but the rest is private.
First of all 'properties' could refer to different things in different languages. For example, in Java you would be meaning instance variables, whilst C# has a distinction between the two.
I'm going to assume you mean instance variables since you mention getters/setters.
The reason as others have mentioned is Encapsulation. And what does Encapsulation buy us?
Flexibility
When things have to change (and they usually do), we are much less likely to break the build by properly encapsulating properties.
For example we may decide to make a change like:
int getFoo()
{
return foo;
}
int getFoo()
{
return bar + baz;
}
If we had not encapsulated 'foo' to begin with, then we'd have much more code to change. (than this one line)
Another reason to encapsulate a property, is to provide a way of bullet-proofing our code:
void setFoo(int val)
{
if(foo < 0)
throw MyException(); // or silently ignore
foo = val;
}
This is also handy as we can set a breakpoint in the mutator, so that we can break whenever something tries to modify our data.
If our property was public, then we could not do any of this!

Delphi - Declaring in class or not?

Just recently, probably because I've been maintaining some old code, I've started to look at how / why I do things. As you do.
Most of my Delphi programming has been picked up in house, or from examples scattered across the web or manuals. And in some things are done just because "that's how I do it"
What I'm currently wondering about is Declaration, of variables, procedures, functions, etc.
When I am working with a form, I will place all my procedures and functions under public or private. Whilst I will try to avoid global vars and constants will generally go under var or const, either in the interface or implementation, depending on where they need to be called (occasionally though they will go in public / private)
Otherwise, if its just a unit I will declare the procedure in the interface and use in the implementation. Some of the code I've been maintaining recently has no interface declaration but instead has everything properly ordered with calls after procedures...
Is there a correct way to do this? Are there rules of what should / should not go in the class? Or is it a style / when you started thing?
Edit to add
My question is not about whether a declaration of a procedure goes in private/public but whether all declarations in a TForm Unit should go in one of these. Similarly should var / const be in one or the other?
Further clarification
I understand that not declaring in interface, or declaring in public/private/etc affects the visibility of procedures/functions to other units in my applicaiton.
The core of my question is why would i not want to declare? - especially when working in a form/unit when placing in private is much more explicit that the thing declared is not available to other units...
Cheers
Dan
Everything that can have a different value depending on the concrete instance belongs to the class, i.e.
TDog = class
strict private
FColor : TColor;
FName : String;
public
property Color : TColor read FColor write FColor;
property Name : String read FName write FName;
end;
Color and name are clearly attributes of each dog (and each dog will have other values here).
General rules:
Fields belong in private (visible in this class and in this unit) or strict private (visible only in this class)
If you need access to fields from other classes, create a public property. This gives you the freedom to change the simple field access to a more sophisticated getter / setter method lateron without changing the interface of your class.
Everything should be as local as possible. If private is enough, there's no need to make it protected (visible in subclasses too). And only make those things public that you really need from the outside.
Forms: only those things that you want to be stored in the DFM file should be published.
Put as much as you can in the implementation section and as little as you can in the interface section. This is also true for uses clauses.
You might be confusing the term global variable. If it's declared in a class it's not a global variable (even if declared public). Global variables (which you correctly consider good to avoid) always go in a var section either in the interface or the implementation section (which is preferrable following the general rules above)
The question seems to deal with scope. In other words, how easily accessible things can or should be.
As a general guideline, you want to reduce the scope of things as much as possible but still keep them accessible enough to be reused. The reason for this is:
that as your system grows and becomes more complex, the things that have are larger scope are more easily accessible.
as a result, they are more likely to be reused in an uncontrolled fashion.
(sounds great) but the problem comes when you want to make changes, and many things use that which you want to change...
it becomes far more difficult to make your changes without breaking something else.
Having said that, there is also a distinction between data (variables, constants, class fields, record attributes) and routines (functions, procedures, methods on classes). You'll want to apply the guidelines far more strictly to data because 'strange use' of data could interfere with some of your routines in highly unexpected and hard to debug ways.
Another thing to bear in mind is the special distinction between global variables and class fields or record attributes:
using global variables there is only one 'value' (term used loosely) for the entire application.
using class fields or record attributes, each new instance of the class or record has its own values independent of other instances.
This does seem to imply that you could use some form of global whenever your application only needs one thing. However, as alluded to earlier: this is not the only reason to avoid globals.
Personally I even tend to avoid global routines.
I'm frequently discovering that things that seemed okay declared global are not as universal as first thought. (E.g. Delphi VCL declares a global Screen object, I work on 2 screens; and many of our clients use 4 to 6.)
I also find it useful to associate routines that could have been global with specific classes as class methods. It generally makes it easier to understand the code.
So listing these 'locations' from largest scope to smallest, you would generally strive to pick locations lower down in the list (especially for data).
interface global
implementation global
interface threadvar
implementation threadvar
published (Note I don't really consider this to be a scope identifier; it's really public scope; "and includes RTTI information" - theoretically, it would be useful to also mark some private attributes as "include RTTI".)
public
protected
private
strict private
local variable
I must confess: what I have presented here is most certainly an over-simplification. It is one thing to know the goals, another to actually implement them. There is a balancing act between encapsulation (hiding things away) and exposing controlled interfaces to achieve high levels of re-usability.
The techniques to successfully balance these needs fall into a category of far more complicated (and sometimes even contentious) questions on system design. A poor design is likely to induce one to expose 'too much' with 'too large' a scope, and (perhaps paradoxically) also reduce re-usability.

Make "private" members behave like "strict private"

What about a feature in an upcoming Delphi version enabling that?
Maybe it could be a compiler switch promoting all **private**s to **strict private**s.
... or it could be a feature of the new non-legacy compiler font-end Nick Hodges was talking about. => private does always behave like strict private.
EDIT: The reason why I want this is because I just don't want to add thousands of stricts to my private modifiers. Furthermore the "strict private" behavior is the default behavior in any object oriented language I'm familiar with!
To quote from the article:
So, we are working to create a “new Delphi” and a new compiler architecture, to keep your existing code working, to emit 64-bit binaries using both Delphi and C++Builder, and maybe a few other kind of binaries while we are at it. And it all has to be done right so that it all works for you.
I interpret that as, if codegear is going to change the behaviour of private. Then they wil proide an option to keep the old behaviour just like they did in the past.
Just for clarification, within a class there are 6 different access levels (ok 7 but automated is deprecated).
public: Anything that can access the object can access this.
protected: Methods in the class and its subclasses and anything in the same unit can access.
strict protected: Methods in the class and its subclasses can access.
private: Methods in the class and anything in the same unit can access.
strict private: Methods in the class.
published: As public buth with runtime information for the object inspector.
The current private implementation is private to everything outside the unit it is declared in. So if your reasoning for not wanting to add the strict statements is that you don't want to modify your existing units, then you have nothing to gain except breaking any existing code that accesses the class in the same unit. As long as your existing units are not modified, then the difference between strict and non-strict private is academic.
If your reasoning for the strict behavior is to use the compiler to help you refactor code that takes advantage of the less-private behavior, then adding the strict to one class at a time is a good incremental approach so you can get to a compilable and testable state more often. A whole sale change of behavior would require fixing every violation before you knew if any of them worked.
The reason private behaves like it does is similar to C++'s friend - it allows certain classes (or procedural code) to access private members. The VCL and RTL makes heavy use of this behavior, so a compiler switch or an all out change would break all of that code.
Delphi's implementation of private is private enough for all practical purposes since typically you control the unit your class is declared in. If you only ever declare one class per unit, and never include procedural code, then the difference is only academic.
I don't quite understand the question. But why would you need this feature? Why not just replace Privates in your code with Strict Privates if that is what you desire?
I expected your reason for wanting to change the meaning of private was that you wanted the stricter behavior without having to break backward compatibility. I figured you were producing a library that you wished to be usable with Delphi 7 and prior, which don't have the strict modifier.
But if that's not your reason, then I don't think you've got much to work with. You can convert all your private code to strict private pretty easily with a simple script.
perl -i.bak -pe 's/(?<!\bstrict )\b(private|protected)\b/strict $1/ig' *.pas
That takes any private or protected that isn't already strict and puts strict in front of it. It modifies the files in-place. (Beware; it may insert "strict" into string literals, too.)
So anyway, I don't think we're going to see private become strict anytime soon. Doing that could break old code, and there's not really much practical gain from it. It lets purists have "more pure" code, but they can already have that simply by using strict. I think that if we were ever going to have "default strict" visibility, then the time for the change was when strict was introduced in the first place. But as things are today, we already have a way of getting strict visibility specifiers, so there's no need for another change.

Resources