I'm studying about operating system, and i cant understand about processes resource sharing.
In ppt, it says
Process Creation (title)
*Resource sharing
Parent and children share all resources
Parent and child share no resources
with my poor english, can not understand why children is sharing all resources and why child share no resources.
This is an abstraction over the very concrete fork function. I guess for academical purposes.
When a sub-process is spawned using fork, it inheritates the parent's process opened handles, files, console input/output, and anonymous pipes. These are the resources your document is talking about.
There are other ways for process to share resources, it is by using named pipes, and named files. A file can be memory mapped so this effectively just creates a shared buffer space.
This is all relative to IPC : Inter Process Communication.
Frankly, it is not very important to deal with this things on an abstracted level like your course seems to be doing. Your teachers should just go with concrete terms, concrete function names, and take POSIX as a base. Students will figure the generalization themselves.
Related
Encapsulation lends itself to hierarchical "silos" or "trees" of objects, with a given application's major functionalities decomposed into core trunks, each further decomposed into sub-functionalities instantiated as sub-branch member objects of their respective branches.
As an example, suppose I'm programming a GUI in QT. To separate GUI elements from business logic, for every widget I have a class for the GUI elements, a class for the business logic associated with the GUI elements, and what I'll call a controller which serves as a container for both and exists primarily to pass signals/slots in between. I understand this pattern to be called dependency injection.
Let's suppose our application has 2 windows A and B.
Window A contains 2 independent widgets that have separate business functions i and ii, so we might have the structure A::i and A::ii, where :: is "contains an instance of" and not "extends".
Then i and ii both contain gui and business logic units, so we have A::i::business and A::i::gui.
Now, suppose A::i::business and A::ii::business want to pass information between each other, or engage in bidirectional communication with the model-view for my database, identified as MV. Generally speaking, what are my options for doing this?
What I've thought of so far:
1) Pass signals up and down the tree, i.e., the Verilog solution. This seems the most strictly object oriented, but most tedious.
2) Have a flatter architecture to ease the implementation of solution 1). This hurts encapsulation.
3) Make A::i::business and A::ii::business public all the way down, and have either the other object or a third-party shared class access A::i::business or A::ii:business directly. This hurts encapsulation.
4) Have a relatively unencapsulated object, like the database MV or some other form of "shared storage", exist in a public form near the top level of the program with few/ no super-containers. This seems most appealing, as the relatively encapsulated objects can stay encapsulated and communicate through unidirectional reading/ writing to something that's unencapsulated. However, if I want other objects to perform actions based on changes shared storage, some way of notifying the dependent objects while keeping them private is necessary. This might be called the "multi-threading inspired" or "multi-processing inspired" model of communication.
And any other suggestions you all may have.
I've read this post here, but at my level of understanding, the solutions in the accepted answer such as controller, listener and pub-sub, refer to general design patterns that don't seem to commit to a solution for the concrete problem of how to route signals and make decisions about public/ private accessibility of member classes. It may be the case that these solutions have associated conventions for where the communication objects go and how they access the different variables in either silo that I'm not familiar with.
Most generally speaking, I seem to be running into a general problem of communication across container-trees in well-encapsulated programming.
For future reference, is there a general term for this problem to aide future searching? Is my architectural approach of having the object-container structure directly reflecting the tree-decomposition of application functionality lending itself to too hierarchical a design, and would a different pattern of object containment and cross-branch communication be more optimal?
I have problems understanding the statement low in coupling and high in cohesion. I have googled and read a lot about this, but still finding it hard to understand.
To what I understand is High cohesion means, that we should have classes that are specialized to perform a particular function. Hope this is correct? Like a credit card validation class, which is specialized to validate credit cards only.
And still don't understand what low Coupling means?
What I believe is this:
Cohesion refers to the degree to which the elements of a module/class belong together, it is suggested that the related code should be close to each other, so we should strive for high cohesion and bind all related code together as close as possible. It has to do with the elements within the module/class.
Coupling refers to the degree to which the different modules/classes depend on each other, it is suggested that all modules should be independent as far as possible, that's why low coupling. It has to do with the elements among different modules/classes.
To visualize the whole picture will be helpful:
The screenshot was taken from Coursera.
Cohesion in software engineering, as in real life, is how much the elements consisting a whole(in our case let's say a class) can be said that they actually belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.
One way of looking at cohesion in terms of OO is if the methods in the class are using any of the private attributes.
Now the discussion is bigger than this but High Cohesion (or the cohesion's best type - the functional cohesion) is when parts of a module are grouped because they all contribute to a single well-defined task of the module.
Coupling in simple words, is how much one component (again, imagine a class, although not necessarily) knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.
Loose coupling is a method of interconnecting the components in a system or network so that those components, depend on each other to the least extent practically possible…
I wrote a blog post about this. It discusses all this in much detail, with examples etc. It also explains the benefits of why you should follow these principles.
In software design high cohesion means that class should do one thing and one thing very well. High cohesion is closely related to Single responsibility principle.
Low coupling suggest that class should have least possible dependencies. Also, dependencies that must exist should be weak dependencies - prefer dependency on interface rather than dependency on concrete class, or prefer composition over inheritance .
High Cohesion and low coupling give us better designed code that is easier to maintain.
Short and clear answer
High cohesion: Elements within one class/module should functionally belong together and do one particular thing.
Loose coupling: Among different classes/modules should be minimal dependency.
Low coupling is in the context of two or many modules. If a change in one module results in many changes in other module then they are said to be highly coupled. This is where interface based programming helps. Any change within the module will not impact the other module as the interface (the mean of interaction ) between them has not changed.
High cohesion- Put the similar things together. So a class should have method or behaviors to do related job. Just to give an exaggerated bad example: An implementation of List interface should not have operation related to String. String class should have methods, fields which is relevant for String and similarly, the implementation of List should have corresponding things.
Hope that helps.
Cohesion - how closely related everything is with one another.
Coupling - how everything is connected to one another.
Let's take an example - We want to design a self-driving car.
(1) We need the motor to run properly.
(2) We need the car to drive on its own.
All of the classes and functions in (1) starting the motor and making it run work great together, but do not help the car steer. So we place those classes behind an Engine Controller.
All of the classes and functions in (2) work great to make the car steer, accelerate and brake. They do not help the car start or send gasoline to the pistons. So we place these classes behind its own Driving Controller.
These controllers are used to communicate with all of the classes and functions that are available. The controllers then communicate only with each other. This means I can't call a function in the piston class from the gas pedal class to make the car go faster.
The pedal class has to ask the Driving Controller to talk to the Engine Controller which then tells the piston class to go faster. This allows us programmers to be able to find issues and allows us to combine large programs without worrying. This is because the code was all working behind the controller.
Take the example of an old PC motherboard.
Mouse had its own PS/2 port.
Printer had its own Printer port.
Monitor had its own VGA port.
This meant that a particular port was meant only for a particular device, and for none other.
This is Strong / High Coupling
Since a mouse is used only for operating the cursor and related functionalities, a keyboard for typing keys, etc i.e they perform only the task they are intended for, this is High Cohesion
If a mouse had a few buttons 'a' 'b' 'c' to enter, then it is doing more than what it should, since a keyboard is already performing them, this is Low Cohesion
The outdated usage of exclusive ports was thankfully replaced by a standard (interface) we call USB. This is Loose / Low Coupling
Looking at these physical attributes, it looks obvious that this is how it is supposed to be, but while writing software it is very easy to lose track of what functionality is to be put where, etc. and hence as a reminder, in everything in life, always stick to:
'High Cohesion and Loose Coupling'
Metaphorically, if your cat barks, it has poor cohesion, and if your dog needs a cat by his side to bark, it is highly coupled.
"Dogs bark and cats purr, if they barf your pull request will be rejected"
Long story short, low coupling as I understood it meant components can be swapped out without affecting the proper functioning of a system. Basicaly modulize your system into functioning components that can be updated individually without breaking the system
Do you have a smart phone? Is there one big app or lots of little ones? Does one app reply upon another? Can you use one app while installing, updating, and/or uninstalling another? That each app is self-contained is high cohesion. That each app is independent of the others is low coupling. DevOps favours this architecture because it means you can do discrete continuous deployment without disrupting the system entire.
When I was reading about a microservice. I came across the following things:
Cohesion is a measure of the number of relationships that parts of a component have with each other. High cohesion means that all of the parts that are needed to deliver the component's functionality are included in the component
Coupling is a measure of the number of relationships that one component has with other components in the system. Low coupling means that components do not have many relationships with other components
Inheritance or generalization is an example of high coupling (i.e. high interdependence). What I meant by this is that in inheritance often the parent class defines base functionalities that is used by its child class and change in methods of parent class directly impact its child classes. Hence we can say that there is a greater degree of interdependence between classes.
Realization or using interface is an example of high cohesion (i.e. low interdependence). What this means is that an interface put forward a contract for any class that implements it but each class has the right to implement methods declared in interface in its own way and changes in method declared in one class doesn't affect any other class.
Low Coupling:--
Will keep it very simple.
If you change your module how does it impact other modules.
Example:-
If your service API is exposed as JAR, any change to method signature will break calling API (High/Tight coupling).
If your module and other module communicate via async messages. As long as you get messages, your method change signature will be local to your module (Low coupling).
Off-course if there is change in message format, calling client will need to make some change.
Low Coupling and High Cohesion is a recommended phenomenon.
Coupling means to what extent various modules are interdependent and how the other modules are affected on changing some/considerable functionality of a module. Low coupling is emphasized as the dependency has to be maintained low so that very least/negligible changes are made to other modules.
An example might be helpful. Imagine a system which generates data and puts it into a data store, either a file on disk or a database.
High Cohesion can be achieved by separate the data store code from the data production code. (and in fact separating the disk storage from the database storage).
Low Coupling can be achieved by making sure that the data production doesn't have any unnecessary knowledge of the data store (e.g. doesn't ask the data store about filenames or db connections).
Here is an answer from a bit of an abstract, graph theoretic angle:
Let's simplify the problem by only looking at (directed) dependency graphs between stateful objects.
An extremely simple answer can be illustrated by considering two limiting cases of dependency graphs:
The 1st limiting case: a cluster graphs .
A cluster graph is the most perfect realisation of a high cohesion and low coupling (given a set of cluster sizes) dependency graph.
The dependence between clusters is maximal (fully connected), and inter cluster dependence is minimal (zero).
This is an abstract illustration of the answer in one of the limiting cases.
The 2nd limiting case is a fully connected graph, where everything depends on everything.
Reality is somewhere in between, the closer to the cluster graph the better, in my humble understanding.
From another point of view: when looking at a directed dependency graph, ideally it should be acyclic, if not then cycles form the smallest clusters/components.
One step up/down the hierarchy corresponds to "one instance" of loose coupling, tight cohesion in a software but it is possible to view this loose coupling/tight cohesion principle as a repeating phenomena at different depths of an acyclic directed graph (or on one of its spanning tree's).
Such decomposition of a system into a hierarchy helps to beat exponential complexity (say each cluster has 10 elements). Then at 6 layers it's already 1 million objects:
10 clusters form 1 supercluster, 10 superclusters form 1 hypercluster and so on ... without the concept of tight cohesion, loose coupling, such a hierarchical architecture would not be possible.
So this might be the real importance of the story and not just the high cohesion low coupling within two layers only. The real importance becomes clear when considering higher level abstractions and their interactions.
I think you have red so many definitions but in the case you still have doubts or In case you are new to programming and want to go deep into this then I will suggest you to watch this video,
https://youtu.be/HpJTGW9AwX0
It's just reference to get more info about polymorphism...
Hope you get better understanding with this
I just got into using singletons and I just want to evaluate if I'm using it correctly. I've read that singletons are evil. I've only started with game dev't so things like unit testing and multithreading doesn't reach me yet.
I separated the logic of my game into different modules. Each module has a singleton and non-singleton classes (eg. data model). I'm using the singleton as a mediator so it can interact with other modules. This allows me to work with other people since it's in manageable pieces and I only need to expose the helper methods of my singleton. He doesn't need to know how I implemented it.
Am I doing the right thing?
Examples:
In a traditional japanese SRPG game (like FFTactics), the cells/grid for the tilemap has its own module. The character interacts with the singleton of this module.
All my sprites are generated by an AssetManager (a singleton) which autoscales the sprite depending on the resolution-availability and resolution of the device. This is done just by a calling a method in the singleton.
I definitely don't agree that singletons are evil. They are sometimes overused perhaps but on some occasions are just perfect for the job. In some applications it makes sense to have some kind of general data manager. The singleton pattern is used extensively in the SDK itself (app delegates, shared managers, default centers and so on). Most often these are not "pure" singletons, as in you can access a shared instance but can also create new instances if necessary.
The question you need to ask yourself is whether it would be useful to have access to a single instance of a data manager from anywhere at anytime, if it isn't then a singleton is probably not needed. If you are going to be using singletons in multi-threaded environments however, you do need to worry about race conditions (can one thread modify a resource while another is accessing it), the documentation has good explanations on how best to achieve this in Cocoa.
You could easily do that with an instance too.
Let's say you have a GameMap class and a Tile class. The GameMap represents a 2 dimension grid of Tile objects. (This is your FFTactics example).
GameMap *gameMap = [[GameMap alloc] init];
NSArray *theTiles = gameMap.tiles;
The instance of the GameMap owns the grid of tiles, and creates the tiles when the game map is created. No singleton needed.
You may say "but I only have one GameMap at a time, what's the big deal?". What about loading saved games, or loading new levels? Well that becomes as easy as:
// In whatever class object owns the game map
self.gameMap = [[GameMap alloc] initWithSaveData:saveData];
In conclusion, create an instance of a class that has code to manage other instances of things. Keep as little global as possible and your code will be more scalable and maintainable.
I am trying to program an application for the mac to query a high performance computing cluster about its running and queued calculation jobs. The aim is to be able to monitor the submitted jobs if they are still queued and waiting for execution or if they are running and on which node or host in the cluster.
On the GUI side I would like to be able to display an NSTableView showing all submitted job and alternatively a second option to see all hosts in the cluster, how many and which jobs are running on each node.
The model objects themselves are not so hard to do, what bothers me most is the lifecycle and the ownership relations between the host and the job objects. This has to be well designed otherwise I will run into memory management problems.
Please note that I would like to program it without using CoreData if possible.
1. Possibility
The yellow queue object is the root object of my object graph and it owns all the host objects (has an NSArray of custom host objects). Each host object owns all the job object which are running on this host (also by having an NSArray of custom job objects). I think that there are two major problems with this approach:
where are all the job objects store which are still queued and are not already running on a host. They lack a parent host object.
How would one implement a NSTableView containing all the job objects?
2. Possibility
The yellow root object holds directly references to all job objects by having them stored in a NSArray. Each job has an instance variable retaining a host object. Again here are some problems
I would also have the hosts in the model which are currently idle, so no job is currently executed on them.
How would one implement the data source for a NSTableView showing all the hosts.
How does one make sure that there are no duplicate host objects, so that each host in the cluster is represented by one host object only.
My questions are:
1. Which of the two possibilities make most sense? Are there alternatives?
2. Would one better implement it with CoreData?
3. How would one manage the object lifecycle so that there are no retain cycles or dangling pointers.
Thank you
If your concerned about memory management, Core Data is the way to go. It's much more efficient memory wise and it manages memory for you in the vast majority of cases.
In general you manage memory by making sure that each individual class' instances clean up after themselves. Then you put the objects in a hierarchy such that as each level deallocates it automatically cleans up the objects under it.
As to the specific structure, it depends on the logic of the situation you are modeling. If the organization logically goes:
queue{
jobs{
host
}
}
... then you should mimic that in your data structure.
I strongly recommend you use Core Data. You will end up duplicating a lot Core Data functionality anyway if you implement this all by hand. Core Data was designed specifically to manage object graphs like this. That is its primary role. All the database stuff was tacked on as an after thought. There's no need to reinvent the wheel.
For a 2D game I'm making (for Android) I'm using a component-based system where a GameObject holds several GameComponent objects. GameComponents can be things such as input components, rendering components, bullet emitting components, and so on. Currently, GameComponents have a reference to the object that owns them and can modify it, but the GameObject itself just has a list of components and it doesn't care what the components are as long as they can be updated when the object is updated.
Sometimes a component has some information which the GameObject needs to know. For example, for collision detection a GameObject registers itself with the collision detection subsystem to be notified when it collides with another object. The collision detection subsystem needs to know the object's bounding box. I store x and y in the object directly (because it is used by several components), but width and height are only known to the rendering component which holds the object's bitmap. I would like to have a method getBoundingBox or getWidth in the GameObject that gets that information. Or in general, I want to send some information from a component to the object. However, in my current design the GameObject doesn't know what specific components it has in the list.
I can think of several ways to solve this problem:
Instead of having a completely generic list of components, I can let the GameObject have specific field for some of the important components. For example, it can have a member variable called renderingComponent; whenever I need to get the width of the object I just use renderingComponent.getWidth(). This solution still allows for generic list of components but it treats some of them differently, and I'm afraid I'll end up having several exceptional fields as more components need to be queried. Some objects don't even have rendering components.
Have the required information as members of the GameObject but allow the components to update it. So an object has a width and a height which are 0 or -1 by default, but a rendering component can set them to the correct values in its update loop. This feels like a hack and I might end up pushing many things to the GameObject class for convenience even if not all objects need them.
Have components implement an interface that indicates what type of information they can be queried for. For example, a rendering component would implement the HasSize interface which includes methods such as getWidth and getHeight. When the GameObject needs the width, it loops over its components checking if they implement the HasSize interface (using the instanceof keyword in Java, or is in C#). This seems like a more generic solution, one disadvantage is that searching for the component might take some time (but then, most objects have 3 or 4 components only).
This question isn't about a specific problem. It comes up often in my design and I was wondering what's the best way to handle it. Performance is somewhat important since this is a game, but the number of components per object is generally small (the maximum is 8).
The short version
In a component based system for a game, what is the best way to pass information from the components to the object while keeping the design generic?
We get variations on this question three or four times a week on GameDev.net (where the gameobject is typically called an 'entity') and so far there's no consensus on the best approach. Several different approaches have been shown to be workable however so I wouldn't worry about it too much.
However, usually the problems regard communicating between components. Rarely do people worry about getting information from a component to the entity - if an entity knows what information it needs, then presumably it knows exactly what type of component it needs to access and which property or method it needs to call on that component to get the data. if you need to be reactive rather than active, then register callbacks or have an observer pattern set up with the components to let the entity know when something in the component has changed, and read the value at that point.
Completely generic components are largely useless: they need to provide some sort of known interface otherwise there's little point them existing. Otherwise you may as well just have a large associative array of untyped values and be done with it. In Java, Python, C#, and other slightly-higher-level languages than C++ you can use reflection to give you a more generic way of using specific subclasses without having to encode type and interface information into the components themselves.
As for communication:
Some people are making assumptions that an entity will always contain a known set of component types (where each instance is one of several possible subclasses) and therefore can just grab a direct reference to the other component and read/write via its public interface.
Some people are using publish/subscribe, signals/slots, etc., to create arbitrary connections between components. This seems a bit more flexible but ultimately you still need something with knowledge of these implicit dependencies. (And if this is known at compile time, why not just use the previous approach?)
Or, you can put all shared data in the entity itself and use that as a shared communication area (tenuously related to the blackboard system in AI) that each of the components can read and write to. This usually requires some robustness in the face of certain properties not existing when you expected them to. It also doesn't lend itself to parallelism, although I doubt that's a massive concern on a small embedded system...?
Finally, some people have systems where the entity doesn't exist at all. The components live within their subsystems and the only notion of an entity is an ID value in certain components - if a Rendering component (within the Rendering system) and a Player component (within the Players system) have the same ID, then you can assume the former handles the drawing of the latter. But there isn't any single object that aggregates either of those components.
Like others have said, there's no always right answer here. Different games will lend themselves towards different solutions. If you're building a big complex game with lots of different kinds of entities, a more decoupled generic architecture with some kind of abstract messaging between components may be worth the effort for the maintainability you get. For a simpler game with similar entities, it may make the most sense to just push all of that state up into GameObject.
For your specific scenario where you need to store the bounding box somewhere and only the collision component cares about it, I would:
Store it in the collision component itself.
Make the collision detection code work with the components directly.
So, instead of having the collision engine iterate through a collection of GameObjects to resolve the interaction, have it iterate directly through a collection of CollisionComponents. Once a collision has occurred, it will be up to the component to push that up to its parent GameObject.
This gives you a couple of benefits:
Leaves collision-specific state out of GameObject.
Spares you from iterating over GameObjects that don't have collision components. (If you have a lot of non-interactive objects like visual effects and decoration, this can save a decent number of cycles.)
Spares you from burning cycles walking between the object and its component. If you iterate through the objects then do getCollisionComponent() on each one, that pointer-following can cause a cache miss. Doing that for every frame for every object can burn a lot of CPU.
If you're interested I have more on this pattern here, although it looks like you already understand most of what's in that chapter.
Use an "event bus". (note that you probably can't use the code as is but it should give you the basic idea).
Basically, create a central resource where every object can register itself as a listener and say "If X happens, I want to know". When something happens in the game, the responsible object can simply send an event X to the event bus and all interesting parties will notice.
[EDIT] For a more detailed discussion, see message passing (thanks to snk_kid for pointing this out).
One approach is to initialize a container of components. Each component can provide a service and may also require services from other components. Depending on your programming language and environment you have to come up with a method for providing this information.
In its simplest form you have one-to-one connections between components, but you will also need one-to-many connections. E.g. the CollectionDetector will have a list of components implementing IBoundingBox.
During initialization the container will wire up connections between components, and during run-time there will be no additional cost.
This is close to you solution 3), expect the connections between components are wired only once and are not checked at every iteration of the game loop.
The Managed Extensibility Framework for .NET is a nice solution to this problem. I realize that you intend to develop on Android, but you may still get some inspiration from this framework.