Let's talk about theory a bit. We have one container, let's call it TMyObj that looks like this:
struct TMyObj{
bool bUpdated;
bool bUnderUpdate;
}
Let a class named TMyClass have an array of the container above + 3 helpful functions. One for getting an object to be updated. One for adding update info to a certain object and one for getting an updated object. It's also called in this order. Here's the class
class TMyClass{
TmyObj entries[];
TMyObj GetObjToUpdate;
{
//Enter critical section
for(int i=0; i<Length(entries); i++)
if(!entries[i].bUnderUpdate)
{
entries[i].bUnderUpdate=true;
return entries[i];
}
//Leave critical section
}
//the parameter here is always contained in the Entries array above
void AddUpdateInfo(TMyObj obj)
{
//Do something...
//Enter critical section
if(updateInfoOver) obj.bUpdated=true; //left bUnderUpdate as true so it doesn't bother us
//Leave critical section
}
TmyObj GetUpdatedObj
{
//<-------- here
for(int i=0; i<Length(entrues); i++)
if(entries[i].bUpdated) then return entries[i];
//<-------- and here?
}
}
Now imagine 5+ threads using the first two and another one for using the last function(getUpdadtedObj) on one instance of the class above.
Question: Will it be thread-safe if there's no critical section in the last function?
Given your sample code, it appears that it would be thread-safe for a read. This is assuming entries[] is a fixed size. If you are simply iterating over a fixed collection, there is no reason that the size of the collection should be modified, therefore making a thread-safe read ok.
The only thing I could see is that the result might be out of date. The problem comes from a call to GetUpdatedObj -- Thread A might not see an update to entries[0] during the life-cycle of
for(int i=0; i<Length(entrues); i++)
if(entries[i].bUpdated) then return entries[i];
if Thread B comes along and updates entries[0] while i > 0 -- it all depends if that is considered acceptable or not.
Related
V8's garbage collection seems to easily clean up as it goes a Local<T> value where T anything stored in the Local, however if you create an ObjectTemplate and then create an instance of that Object, v8 will wait to clean up the memory. Consider the following example where the resident set size remains stable throughout program execution:
Isolate* isolate = Isolate::New(create_params);
Persistent<Context> *context= ContextNew(isolate); // creates a persistent context
for(int i = 1 ; i <= 1000000; i ++ ) {
isolate->Enter();
EnterContext(isolate, context); // enters the context
{
HandleScope handle_scope(isolate);
Local<Object> result = Object::New(isolate);
}
ExitContext(isolate, context);
isolate->Exit();
}
Above, all we do is create a new Object in a loop, and then handle_scope goes out of scope and it looks like the Local values allocated are garbage collected right away as the residential set size remains steady. However, there is an issue when this object is created through an ObjectTemplate that is also created in the loop:
Isolate* isolate = Isolate::New(create_params);
Persistent<Context> *context= ContextNew(isolate); // creates a persistent context
for(int i = 1 ; i <= 1000000; i ++ ) {
isolate->Enter();
EnterContext(isolate, context); // enters the context
{
HandleScope handle_scope(isolate);
Local<Object> result;
Local<ObjectTemplate> templ = ObjectTemplate::New(isolate);
if (!templ->NewInstance(context->Get(isolate)).ToLocal(&result)) { exit(1); }
}
ExitContext(isolate, context);
isolate->Exit();
}
Here, the resident set size increases linearly until an unnecessary amount of ram is used for such a small program. Just looking to understand what is happening here. Sorry for the long explanation, i tried to keep it short and to the point :p. Thanks in advance!
V8 assumes that ObjectTemplates are long-lived and hence allocates them in the "old generation" part of the heap, where it takes longer for them to get collected by a (comparatively slow and rare) full GC cycle -- if the assumption was right and they actually are long-lived, this is an overall performance win. Objects themselves, on the other hand, are allocated in the "young generation", where they are quick and easy to collect by the (comparatively frequent) young-generation GC cycles.
If you run with --trace-gc you should see this explanation confirmed.
I want to be able to do something like this:
for(i = 0; i < 10; i++) {
//if any button in the array is pressed, disable it.
button[i].setOnAction( ae -> { button[i].setDisable(true) } );
}
However, I get a error saying "local variables referenced from a lambda expression must be final or effectively final". How might I still do something like the code above (if it is even possible)? If it can't be done, what should be done instead to get a similar result?
As the error message says, local variables referenced from a lambda expression must be final or effectively final ("effectively final" meaning the compiler can make it final for you).
Simple workaround:
for(i = 0; i < 10; i++) {
final int ii = i;
button[i].setOnAction( ae -> { button[ii].setDisable(true) } );
}
Since you are using lambdas, you can benefit also from other features of Java 8, like streams.
For instance, IntStream:
A sequence of primitive int-valued elements supporting sequential and parallel aggregate operations. This is the int primitive specialization of Stream.
can be used to replace the for loop:
IntStream.range(0,10).forEach(i->{...});
so now you have an index that can be used to your purpose:
IntStream.range(0,10)
.forEach(i->button[i].setOnAction(ea->button[i].setDisable(true)));
Also you can generate a stream from an array:
Stream.of(button).forEach(btn->{...});
In this case you won't have an index, so as #shmosel suggests, you can use the source of the event:
Stream.of(button)
.forEach(btn->btn.setOnAction(ea->((Button)ea.getSource()).setDisable(true)));
EDIT
As #James_D suggests, there's no need of downcasting here:
Stream.of(button)
.forEach(btn->btn.setOnAction(ea->btn.setDisable(true)));
In both cases, you can also benefit from parallel operations:
IntStream.range(0,10).parallel()
.forEach(i->button[i].setOnAction(ea->button[i].setDisable(true)));
Stream.of(button).parallel()
.forEach(btn->btn.setOnAction(ea->btn.setDisable(true)));
Use the Event to get the source Node.
for(int i = 0; i < button.length; i++)
{
button[i].setOnAction(event ->{
((Button)event.getSource()).setDisable(true);
});
}
Lambda expressions are effectively like an annonymous method which works on stream. In order to avoid any unsafe operations, Java has made that no external variables which can be modified, can be accessed in a lambda expression.
In order to work around it,
final int index=button[i];
And use index instead of i inside your lambda expression.
You say If the button is pressed, but in your example all the buttons in the list will be disabled. Try to associate a listener to each button rather than just disable it.
For the logic, do you mean something like that :
Arrays.asList(buttons).forEach(
button -> button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setEnabled(false);
}
}));
I Also like Sedrick's answer but you have to add an action listener inside the loop .
I was wondering how I would go about getting a different set of data to print every time I press the same key for KeyPressed in Processing. The data being displayed is from an imported file so the code for what I'm doing is as follows:
import java.util.Scanner;
import java.io.*;
PImage cityMap;
FileInputStream in;
int Year=0;
void setup()
{
size(500,500);
cityMap=loadImage("cityMap.png");
background(cityMap);
}
void draw()
{
//EMPTY
}
void keyPressed() {
if(key==CODED)
{
if(keyCode==RIGHT)
{
//2015
String fif[]= loadStrings("2015data.txt");
for (int i=1; i<fif.length;i++)
{
Scanner sc= new Scanner(fif[i]);
int xValue= sc.nextInt();
int yValue= sc.nextInt();
int pixelX= locX2PixX(xValue);
int pixelY= locY2PixY(yValue);
stroke(200,200,250);
point(pixelX,pixelY);
}
//2016
String six[]= loadStrings("2016data.txt");
if(
for (int i=1; i<six.length;i++)
{
Scanner sc= new Scanner(six[i]);
int xValue= sc.nextInt();
int yValue= sc.nextInt();
int pixelX2= locX2PixX(xValue);
int pixelY2= locY2PixY(yValue);
stroke(250,200,250);
point(pixelX2,pixelY2);
}
//2017
String seven[]= loadStrings("2017data.txt");
for (int i=1; i<seven.length;i++)
{
Scanner sc= new Scanner(seven[i]);
int xValue= sc.nextInt();
int yValue= sc.nextInt();
int pixelX3= locX2PixX(xValue);
int pixelY3= locY2PixY(yValue);
stroke(20,200,250);
point(pixelX3,pixelY3);
}
}
}
}
int locX2(int locationX)
{
return((int)((6*locationX)-8));
}
int locY2(int locationY)
{
return((int)(8*locationY+8));
}
I managed to get the code to run minus that one feature.
I think I have most of the logic down, I'm just trying to figure out to have this show only one set of the data at a time and then the next one after I press the same key again. I was thinking I may need some type of if statement that could maybe use my year variable?
(I don't know that much about Processing, but it's silly to chat in comments about general purpose computer programming...)
It sounds like you need to maintain "state", which is a fancy way of saying a variable where you store information about if you have done something before, and what that thing is.
First, how many states do you care about? It sounds like you have two distinct options, so if you add the initial state, this technically makes three (but for only two valid states we can ignore that for now). Ok, so your startup code (constructor or initializer, whatever is typical for Processing) will set a variable of some sort to a known start value.
How to do this is up to you. It could be a String or an int or something advanced like an enum. The idea is that this is a testable, settable, persistent chunk of data that you know the meaning of.
Every time you handle the "event" of a button being pushed you do two things:
Test the state you initialized earlier and make a decision. In the initial state you want to load "2015" data. Ok. So do that.
Change the variable holding the state so it is in the "next" state. In the 2015 state we want to change that to 2016 so we are ready for the next button event we handle.
A simple example would be to create an int called dataState or something. In setup set this to 2015. In your button handler have a switch or if statement that checks for all possible values dataState can be, and runs the appropriate code for that state. e.g., if it is set to 2015 it will do whatever you need it to do for 2015, but at the end it should set the dataState to 2016 so that the next time through it does the 2016 branch.
It is up to you what the 2016 branch does to this state. You can reset it to 2015 or continue on to 2017, if your code needs to have that functionality.
Some comments:
You'll notice that your code for processing 2015 data is almost the same as the code that processes 2016 data. This is an opportunity to use a function or method that accepts a filename and does some work based on that, and then sets the state to the "next" state.
Once you do this, then your logic in the button handler becomes a nice short and understandable set of if ... else if statements that simply call the appropriate function for that state. This makes it easy to add, say, 2017 processing. Code always grows features so it's good to plan ahead for that.
Once you get really good at this, you'll start thinking about "state models" and then before you know it you'll want to have your state managed as a class or enum with a big switch statement that drives the whole works. This is a very common pattern with embedded, event driven code that Processing supports.
keep track of your year in a variable and change it when the key is pressed. Something like this
//start off one less than first desired year
int Year=2014;
void keyPressed() {
if(key==CODED) {
if(keyCode==RIGHT) {
//increment year
Year = Year+1;
//Clamp year between 2015 and 2017
Year= Math.max(2015, Math.min(2017, Year));
String yr[]= loadStrings(Year +"data.txt");
for (int i=1; i<yr.length;i++) {
Scanner sc= new Scanner(yr[i]);
int xValue= sc.nextInt();
int yValue= sc.nextInt();
int pixelX= locX2PixX(xValue);
int pixelY= locY2PixY(yValue);
stroke(200,200,250);
point(pixelX,pixelY);
}
}
}
}
I am trying to implement an algorithm in Visual C using Cudd package. I have to use a function recursively. But it keeps throwing an error at one particular line. Error is Access violation reading location 0x00594a5ct. And it is coming against the usage of temp_bdd_result. I am unable to figure out why is this happening because both values used in temp_bdd_result-bdd_node & bdd_result are containing values. So why are they not accessible. Or this error points to some thing else that I am not able to see. Please Help.
DdNode* Path_Function_Construct(DdManager *manager,int matrix[3][3],int source)
{
DdNode *bdd_node,*bdd_result,*e,*temp_bdd_node,*temp_bdd_result;
if (source>=rows)
return Cudd_ReadOne(manager);
else
{
bdd_result=Cudd_ReadZero(manager);
Cudd_Ref(bdd_result);
for (int j=0;j<columns;j++)
{
if (matrix[source][j]==1)
{
//Declaring temp variables
//This means that an edge exists between source and node in consideration
e=Cudd_bddNewVar(manager);
Cudd_Ref(e);
//Removing redundant nodes
int new_matrix[3][3];
for(int l=0;l<rows;l++)
for(int m=0;m<columns;m++)
new_matrix[l][m]=matrix[l][m];
for(int i=0;i<rows;i++)
new_matrix[i][j]=0;
//find path function using that node as a source
temp_bdd_node=Path_Function_Construct(manager,new_matrix,j+1);
Cudd_Ref(temp_bdd_node);
bdd_node=Cudd_bddAnd(manager,e,temp_bdd_node);
Cudd_Ref(bdd_node);
temp_bdd_result=Cudd_bddIthVar(manager,4);
temp_bdd_result=Cudd_bddAnd(manager,bdd_result,bdd_node); //this is where error is coming
Cudd_Ref(temp_bdd_result);
Cudd_RecursiveDeref(manager,bdd_result);
bdd_result=temp_bdd_result;
Cudd_Ref(bdd_result);
Cudd_RecursiveDeref(manager,temp_bdd_node);
Cudd_RecursiveDeref(manager,temp_bdd_result);
Cudd_RecursiveDeref(manager,bdd_node);
Cudd_RecursiveDeref(manager,e);
} // end of if (matrix[source][j]==1)
}// end of for loop
return (bdd_result);
}
}
Cudd_RecursiveDeref() recursively deletes a node and all its child. So whenever bdd_node was dereferenced using Cudd_RecursiveDeref() bdd_result was also removed and its value was not returned by the function. So to retain the value for returning use Cudd_Deref() instead. It just decreases the reference count without deleting its child nodes.
I have a scenario where, at certain points in my program, a thread needs to update several shared data structures. Each data structure can be safely updated in parallel with any other data structure, but each data structure can only be updated by one thread at a time. The simple, naive way I've expressed this in my code is:
synchronized updateStructure1();
synchronized updateStructure2();
// ...
This seems inefficient because if multiple threads are trying to update structure 1, but no thread is trying to update structure 2, they'll all block waiting for the lock that protects structure 1, while the lock for structure 2 sits untaken.
Is there a "standard" way of remedying this? In other words, is there a standard threading primitive that tries to update all structures in a round-robin fashion, blocks only if all locks are taken, and returns when all structures are updated?
This is a somewhat language agnostic question, but in case it helps, the language I'm using is D.
If your language supported lightweight threads or Actors, you could always have the updating thread spawn a new a new thread to change each object, where each thread just locks, modifies, and unlocks each object. Then have your updating thread join on all its child threads before returning. This punts the problem to the runtime's schedule, and it's free to schedule those child threads any way it can for best performance.
You could do this in langauges with heavier threads, but the spawn and join might have too much overhead (though thread pooling might mitigate some of this).
I don't know if there's a standard way to do this. However, I would implement this something like the following:
do
{
if (!updatedA && mutexA.tryLock())
{
scope(exit) mutexA.unlock();
updateA();
updatedA = true;
}
if (!updatedB && mutexB.tryLock())
{
scope(exit) mutexB.unlock();
updateB();
updatedB = true;
}
}
while (!(updatedA && updatedB));
Some clever metaprogramming could probably cut down the repetition, but I leave that as an exercise for you.
Sorry if I'm being naive, but do you not just Synchronize on objects to make the concerns independent?
e.g.
public Object lock1 = new Object; // access to resource 1
public Object lock2 = new Object; // access to resource 2
updateStructure1() {
synchronized( lock1 ) {
...
}
}
updateStructure2() {
synchronized( lock2 ) {
...
}
}
To my knowledge, there is not a standard way to accomplish this, and you'll have to get your hands dirty.
To paraphrase your requirements, you have a set of data structures, and you need to do work on them, but not in any particular order. You only want to block waiting on a data structure if all other objects are blocked. Here's the pseudocode I would base my solution on:
work = unshared list of objects that need updating
while work is not empty:
found = false
for each obj in work:
try locking obj
if successful:
remove obj from work
found = true
obj.update()
unlock obj
if !found:
// Everything is locked, so we have to wait
obj = randomly pick an object from work
remove obj from work
lock obj
obj.update()
unlock obj
An updating thread will only block if it finds that all objects it needs to use are locked. Then it must wait on something, so it just picks one and locks it. Ideally, it would pick the object that will be unlocked earliest, but there's no simple way of telling that.
Also, it's conceivable that an object might become free while the updater is in the try loop and so the updater would skip it. But if the amount of work you're doing is large enough, relative to the cost of iterating through that loop, the false conflict should be rare, and it would only matter in cases of extremely high contention.
I don't know any "standard" way of doing this, sorry. So this below is just a ThreadGroup, abstracted by a Swarm-class, that »hacks» at a job list until all are done, round-robin style, and makes sure that as many threads as possible are used. I don't know how to do this without a job list.
Disclaimer: I'm very new to D, and concurrency programming, so the code is rather amateurish. I saw this more as a fun exercise. (I'm too dealing with some concurrency stuff.) I also understand that this isn't quite what you're looking for. If anyone has any pointers I'd love to hear them!
import core.thread,
core.sync.mutex,
std.c.stdio,
std.stdio;
class Swarm{
ThreadGroup group;
Mutex mutex;
auto numThreads = 1;
void delegate ()[int] jobs;
this(void delegate()[int] aJobs, int aNumThreads){
jobs = aJobs;
numThreads = aNumThreads;
group = new ThreadGroup;
mutex = new Mutex();
}
void runBlocking(){
run();
group.joinAll();
}
void run(){
foreach(c;0..numThreads)
group.create( &swarmJobs );
}
void swarmJobs(){
void delegate () myJob;
do{
myJob = null;
synchronized(mutex){
if(jobs.length > 0)
foreach(i,job;jobs){
myJob = job;
jobs.remove(i);
break;
}
}
if(myJob)
myJob();
}while(myJob)
}
}
class Jobs{
void job1(){
foreach(c;0..1000){
foreach(j;0..2_000_000){}
writef("1");
fflush(core.stdc.stdio.stdout);
}
}
void job2(){
foreach(c;0..1000){
foreach(j;0..1_000_000){}
writef("2");
fflush(core.stdc.stdio.stdout);
}
}
}
void main(){
auto jobs = new Jobs();
void delegate ()[int] jobsList =
[1:&jobs.job1,2:&jobs.job2,3:&jobs.job1,4:&jobs.job2];
int numThreads = 2;
auto swarm = new Swarm(jobsList,numThreads);
swarm.runBlocking();
writefln("end");
}
There's no standard solution but rather a class of standard solutions depending on your needs.
http://en.wikipedia.org/wiki/Scheduling_algorithm