问:
Why don't compilers inline everything?
Sometimes compilers inline function calls. That means that they move the code of the called function into the calling function. This makes things slightly faster because there's no need to push and pop stuff on and off the call stack.

So my question is, why don't compilers inline everything? I assume it would make the executable notably faster.

The only reason I can think of is a significantly larger executable, but does it really matter these days with hundreds of GB of memory? Isn't the improved performance worth it?

Is there any other reason why compilers don't just inline all function calls?

答:
A major limitation is runtime polymorphism. If there is a dynamic dispatch happening when you write foo.bar() then it is impossible to inline the method call. This explains why compilers don't inline everything.

Recursive calls cannot be easily inlined either.

Cross module inlining is also difficult to perform for technical reasons (incremental recompilation would be impossible for ex)

However, compilers do inline a lot of things.

Title: Why don't compilers inline everything?


问:
What to learn to become freelancer?
I have around 8 years experience in software development. I have worked on application development all these years using C++ /win32.

I few years from now I want to become a freelancer . I tried to look into some freelance sites and I am not able to find any projects on C++/win32. I feel C++/Win32 wont help me much and I need to learn new skills . But my job require me to still work on C++ , so I cann't learn any new skills. I can still learn some new skills but without good project , it won't make any sense.

I have shortlisted few skills

php

jquery

perl

python

android

I am still confused which one to start and how to get expertise in them.Any suggestions?

答:
If you are seriously trying to get into freelancing and want to earn serious money, concentrate on the domain, and not programming languages first. For e.g. if you want to get into app development for Android, the real thing is innovating at the application level and user interface level -- coding is the last thing to do here (of course very important though).So you would definitely want to check out statistics of most selling apps, compare and contrast for what works and what does not, generally a fair bit of market research is must.

Of course programming languages matter, but say if you know C++ you should not have too much trouble picking up Java or C# on the job, and as you go along you'd get stronger with whatever language is used in the domain.

The key here is the domain itself -- each has its own problems and you are well advised to read technical journals, trade publications, IEEE and ACM papers or groups that concentrate on industry specific problems etc.

ContentLicense: CC BY-SA 3.0

Title: What to learn to become freelancer?

ContentLicense: CC BY-SA 2.5


答:
First note that one major effect of inline is that it allows further optimizations to be made at the call site.

For your question: there are things which are difficult or even impossible to inline:

dynamically linked libraries

dynamically determined functions (dynamic dispatch, called through function pointers)

recursive functions (tail recursion can)

functions for which you don't have the code (but link time optimization allow this for some of them)

Then inlining has not only beneficial effects:

bigger executable means more disk place and bigger load time

bigger executable means increase of cache pressure (note that inlining small enough functions such as simple getters may decrease the executable size and the cache pressure)

And finally, for functions which takes a non trivial time to execute, the gain just doesn't worth the pain.

Title: Why don't compilers inline everything?

Body:
Sometimes compilers inline function calls. That means that they move the code of the called function into the calling function. This makes things slightly faster because there's no need to push and pop stuff on and off the call stack.

So my question is, why don't compilers inline everything? I assume it would make the executable notably faster.

The only reason I can think of is a significantly larger executable, but does it really matter these days with hundreds of GB of memory? Isn't the improved performance worth it?

Is there any other reason why compilers don't just inline all function calls?


问:
How to test generated file without hardcoding name generation logic?
I have a unit I'm testing which generates a file name and saves something there.  I will need to pull the file out of that location to test it was stored right.  I know how the file name is generated, however, hardcoding the logic for file name generation throughout my tests feels like a 'Magic Number' to me.  Is there a better approch?

I thought of pulling the logic that generates the path name out into it's own helper method in the unit I'm testing, and testing that method once, then using that method when I need a path name.  Then I only 'hardcode' the path generation logic in one test where it seems reasonable.  However, if I did pull that method out it would usually be a private method, which brings up the whole question as to how to test it, rather it's fair to make it public just for testing, and is it a code-smell to be testing helper functions at all.

What is the most elegant way of testing something like this?  just hardcode it?

答:
option 1.: mock the name generation code and test it separately.

pro: you control where and what file is used, no random dangling files to clean up.

option 2.: mock writing to the file.

pro: no need to go to the file system at all an instead save to a byte buffer.


问:
Is routing a site with RESTful not the best when you have very long URLs?
I've read a lot about RESTful, but I have always had a hard time figuring out how I'd use it with a very long query string.  This is an in-house project, and it won't always have a simple /someAction or someController/12/14/my-article-I-want-indexed.

I'm not worried about SEO because the application is not on the Internet.

My querystrings are long sets of ?somevar=123456&x=4785&y=394958.......

Most examples for REST I have seen are for SEO and simple web apps like a blog, maybe a CMS.

Is REST not the best practice for a situation where having long URLs with lots of variables in the querystring is the norm?

Here is an example of what looks to me like a non-RESTful way:

http://www.target.com/s?searchTerm=bicycle&category=0%7CAll%7Cmatchallpartial%7Call+categories&lnk=snav_sbox_bicycle

Is this link an illustration bad practice and design?

It's not a super long URL, but it illustrates that not everyone uses REST, if I understand REST.  I know the reasons for REST, pretty URLs, hackable URLs, etc.  I'd like to design my application well but feel like it would be shoehorned into a pattern I don't need.  What is the best practice here?

答:
REST does not mean to not use URL params at all.

Your example demonstrates this very well. You can still see a 'search' as a REST resource. You implement a controller for it, though it only has one or two actions. (But details do not matter much in this case)

Everything data needed to perform the search can then be sent by using params. There is nothing about REST that forbids it. Actually those parts within the URL as used in REST are always 'resource identifiers' which your params are not.

Think of them as similar to the form data you may post from the new action (showing the form) to the create action (creating the new resource based on this form data). It is just normal to use params in REST. (And for SEO reasons you sometimes even see people using very long text identifiers in some places)


问:
From a technical point of view, could JavaScript be compiled instead of interpreted?
The question title speaks for itself. I'm specifically thinking in terms of a Node.js server. Additionally, this question is assuming that you don't need eval().

Also, if this is not possible, why not?

答:
It's easy to compile any language, no matter how dynamic, to machine code. It just won't be efficient machine code, since it will usually do a lot of dispatching based on run time type tags and looking up values in hash tables, much like a (bytecode) interpreter.

In the simplest case, just compile C code like

```<code>#include <some_js_vm.h>

static char[] source = "... JavaScript ...";

int main() {
  js_run(source);
  return 0;
}
</code>```

For JavaScript without eval, there are still several features that require such inefficient machine code when compiled statically:

with, which modifies scope and semantics of variables based on an object's members. This is only a problem because of the next point.

The fields of any object are dynamic (and no, you can't always infer them), meaning code can and will add and remove fields at run time. So objects remain glorified hash tables, and since your compiler is static it can't really pull tricks like "hidden classes" in V8 (which greatly speeds up attribute access for most objects).

new Function(str) and other moral equivalents to eval.

The whole prototype system, and hence all methods are set up at run time, meaning you can't use vtables or such, or even assume you know all prototypes.

Body:
It's easy to compile any language, no matter how dynamic, to machine code. It just won't be efficient machine code, since it will usually do a lot of dispatching based on run time type tags and looking up values in hash tables, much like a (bytecode) interpreter.

In the simplest case, just compile C code like

#include <some_js_vm.h>

static char[] source = "... JavaScript ...";

int main() {
  js_run(source);
  return 0;
}

For JavaScript without eval, there are still several features that require such inefficient machine code when compiled statically:

with, which modifies scope and semantics of variables based on an object's members. This is only a problem because of the next point.

The fields of any object are dynamic (and no, you can't always infer them), meaning code can and will add and remove fields at run time. So objects remain glorified hash tables, and since your compiler is static it can't really pull tricks like "hidden classes" in V8 (which greatly speeds up attribute access for most objects).

new Function(str) and other moral equivalents to eval.

The whole prototype system, and hence all methods are set up at run time, meaning you can't use vtables or such, or even assume you know all prototypes.


答:
In fact, Javascript is (inside several major browsers) often "compiled" using Just-in-Time compilation techniques (read about the V8 Javascript engine). But as delnan explained, there are case where it is not worthwhile. AFAIK some implementations use Tracing JIT compilation techniques.

And eval could be implemented by calling the compiler. Several Lisp implementations (notably SBCL) are doing that (and Lisp can be as dynamic as Javascript).

And asmjs.org defines a specification of a subset of Javascript which is designed to be easy to compile.

Title: From a technical point of view, could JavaScript be compiled instead of interpreted?

Body:
The question title speaks for itself. I'm specifically thinking in terms of a Node.js server. Additionally, this question is assuming that you don't need eval().

Also, if this is not possible, why not?


答:
Inlining everything would not mean just increased disk memory consumption but also increased internal memory consumption which is not that plentiful. Remember that code also relies in memory in code segment; if a function is called from 10000 places (say the ones from standard libraries in a fairly large project), then the code for that function occupies 10000 times more internal memory.

Another reason might be the JIT compilers; if everything is inline then there are not hot spots to be dynamically compiled.

Title: Why don't compilers inline everything?


答:
First, you cannot always inline, e.g. recursive functions might not be always inlinable (but a program containing a recursive definition of fact with just a printing of fact(8) could be inlined).

Then, inlining is not always beneficial. If the compiler inlines so much that the result code is big enough to have its hot parts not fitting in e.g. the L1 instruction cache, it might be much slower than the non-inlined version (which would easily fit the L1 cache)... Also, recent processors are very fast at executing a CALL machine instruction (at least to a known location, i.e. a direct call, not a call thru pointer).

At last, full inlining requires a whole program analysis. This might not be possible (or is too costly). With C or C++ compiled by GCC (and also with Clang/LLVM) you need to enable link-time optimization (by compiling and linking with e.g. g++ -flto -O2) and that takes quite a lot of compilation time.

Title: Why don't compilers inline everything?


问:
Why did GCC switch from Bison to a recursive descent parser for C++ and C?
Was there a language change that required it or some practical reason why Bison was no longer appropriate or optimal?

I saw on wikipedia that they switched, referring to the GCC 3.4 and GCC 4.1 release notes.

These release notes state:

A hand-written recursive-descent C++ parser has replaced the
  YACC-derived C++ parser from previous GCC releases. The new parser
  contains much improved infrastructure needed for better parsing of C++
  source codes, handling of extensions, and clean separation (where
  possible) between proper semantics analysis and parsing. The new
  parser fixes many bugs that were found in the old parser.

And:

The old Bison-based C and Objective-C parser has been replaced by a
  new, faster hand-written recursive-descent parser

What I would like to know is what actual problems were they having and why it was impossible / impractical to solve using Bison

答:
GCC switched to hand-written parsing because error messages are more meaningful when using recursive descent techniques, as I explained here.

Also, C++ is becoming such a (syntactically) complex language to parse that using parser generators is not worthwhile for it.

At last, the bulk of the work of a real compiler is not parsing, it is optimizing. GCC middle end optimization passes are much more complex than its parsing.

(BTW you can customize GCC e.g. with plugins or using MELT, but you cannot really extend the syntax of the language it is accepting - except by adding attributes and pragmas).


问:
Can TCP/IP Sequence and Acknowledgement numbers be controlled?
Normally TCP/IP Sequence and Acknowledge numbers are 32 bit. However, I need a way to shorten them to be 24 bit (it's an experiment in deep inspection firewalls).

Question: Is it possible to shorten the bit resolution of the Seq/Ack numbers in windows without the knowledge of the application? (which in this case is IIS)

I want to use those top 8 bits to store some session information.

答:
Can we reduce the sequence number ?
As Billy Mailman pointed out theoretically yes you can do it.

Should you do it ?

No,

Why ?

Because every other system in the world will expect the syn/ack sequence number to be of certain length and their TCP stack will be written to parse the standard lengths of each field.So even if your system creates a syn with 24 bits the end system will reply with syn/ack with a sequence number of 32 bit you cannot control that and your system must be smart enough to understand that.You will also face integration issues with other third party devices for the same reason.
And in the second scenario where the end device initiates the connection you will nevertheless have to send 32 bit sequence number
So to do all this you have to create your own TCP stack at the least you have to modify existing ones to suit you and if you manage to do that you ll have minimal or no support for  the stack you modified.

How else can we do it ?

It is always best to stick to standards if you want to scale your applications at least with regards to networking standards like TCP. As Ross Patterson pointed out use tcp options. client program can be easily written to set options but messing with sequence numbers will be a nightmare.

If all you want is some session information do it in your application layer and let your application figure out what information it needs and how best to do it, that way it is much more elegant and simpler than what you are trying to do.


问:
How to verify that library assemblies originate from a given Web site?
How would the following solution be implemented?  Would you need to put this code in each library assembly or just in the main assembly that is determining whether it is safe to call the library assembly based on whether or not it originates from a given intranet Web site?  Also, who should call the CheckSite method - each library assembly or the main app?
Here is the example and solution from a practice exam for the C# Specialist Exam 70-483 that I am referring to:

You are an application developer for a company.  You are creating an
  application on the company’s Web server that will manipulate
  confidential data from business partners.  The application relies on
  many library assemblies in the company intranet to complete its work.
  You are required to verify that every assembly originates from the
  same intranet Web site. Which code should you use to verify the
  current assembly originates from the company intranet?

```<code>public bool CheckSite () {
    SiteMembershipCondition site = new
        SiteMembershipCondition( “http://intranet.company.com” );
    return site.Check( Assembly.GetCallingAssembly().Evidence );
}
</code>```

答:
You shouldn't care what website it comes from, you should be using the strong name (i.e. digitally signed) to verify that the dlls is legitimate.  Then it doesn't matter where you download it from.

See this MSDN article on how to sign with a strong name


答:
Surprising though it may seem, inlining everything doesn't necessarily reduce execution time. The increased size of your code can make it difficult for the CPU to keep all your code in its cache at once. A cache miss on your code becomes more likely and a cache miss is expensive. This is made far worse if your potentially inlined functions are large.

I've had noticeable performance improvements from time to time by taking large chunks of code marked as 'inline' out of header files, put them into the source code, so the code is only in one place rather than at every call site. Then the CPU cache is used better and you also get better compile time...

Title: Why don't compilers inline everything?


答:
One, there are simple examples where inlining everything will work out very badly. Consider this simple C code:

```<code>void f1 (void) { printf ("Hello, world\n"); }
void f2 (void) { f1 (); f1 (); f1 (); f1 (); }
void f3 (void) { f2 (); f2 (); f2 (); f2 (); }
...
void f99 (void) { f98 (); f98 (); f98 (); f98 (); }
</code>```

Guess what inlining everything will do to you.

Next, you make the assumption that inlining will make things faster. That's the case sometimes, but not always. One reason is that code that fits into the instruction cache runs a lot faster. If I call a function from 10 places, I'll always run code that is in the instruction cache. If it is inlined, then the copies are all over the place and run a lot slower.

There are other problems: Inlining produces huge functions. Huge functions are a lot harder to optimise. I've got considerable gains in performance critical code by hiding functions into a separate file to prevent the compiler from inlining them. As a result, the generated code for these functions was much better when they were hidden.

BTW. I don't have "hundreds of GBs of memory". My works computer doesn't even have "hundreds of GBs of hard drive space". And if my application where "hundreds of GBs of memory", it would take 20 minutes just to load the application to memory.

Title: Why don't compilers inline everything?

Body:
One, there are simple examples where inlining everything will work out very badly. Consider this simple C code:

void f1 (void) { printf ("Hello, world\n"); }
void f2 (void) { f1 (); f1 (); f1 (); f1 (); }
void f3 (void) { f2 (); f2 (); f2 (); f2 (); }
...
void f99 (void) { f98 (); f98 (); f98 (); f98 (); }

Guess what inlining everything will do to you.

Next, you make the assumption that inlining will make things faster. That's the case sometimes, but not always. One reason is that code that fits into the instruction cache runs a lot faster. If I call a function from 10 places, I'll always run code that is in the instruction cache. If it is inlined, then the copies are all over the place and run a lot slower.

There are other problems: Inlining produces huge functions. Huge functions are a lot harder to optimise. I've got considerable gains in performance critical code by hiding functions into a separate file to prevent the compiler from inlining them. As a result, the generated code for these functions was much better when they were hidden.

BTW. I don't have "hundreds of GBs of memory". My works computer doesn't even have "hundreds of GBs of hard drive space". And if my application where "hundreds of GBs of memory", it would take 20 minutes just to load the application to memory.


问:
Does this function do one thing only?
Is the following method considered to be doing one thing only?

I'm wondering about that since it takes an optional argument.

```<code>public function findErrors($name = null)
{
    if ($name) {
        return isset($this->errors[$name]) ? $this->errors[$name] : [];
    }

    return $this->errors ?: [];
}
</code>```

If not, would it be better / matter to have it separated like the following:

```<code>public function findErrors()
{
    return $this->errors ?: [];
}

public function findErrorsOf($name)
{
    return isset($this->errors[$name]) ? $this->errors[$name] : [];
}
</code>```

答:
No, not really. It's clearly got two independent paths. It would be better to separate them into two (possibly overloaded) functions to better decouple them.

Better yet, I would look to eliminate the name specific behavior unless it's really that common. What happens if you want to find errors since Thursday? What about errors that contain the word "Banana"? You shouldn't go back to edit this code every time you have a new search criteria - and you shouldn't have one way to find names and another way to find bananas.

Title: Does this function do one thing only?


问:
Is it anti-pattern to mix unit test and web test?
It is a language agnostic question, e.g. I have a unit test like

```<code># Unit test
User user = User.create('john');
assertEquals("User name is john", "john", user.getName());

# Web test start from here
goTo("/user/john");
assertTitleEquals("john");
</code>```

Do you think it is an anti-pattern?
Although I can write a full selenium test suites to do the same thing, but using the above code save much of my time (e.g. no more click('Login'); waitUntil etc, and I don't need to worry if my UI is changed at all, sound like it is a quick and more stable approach to test?

答:
Yes, this is an anti-pattern. "Unit tests should only have one reason to fail." is a common and well known best practice. This test can fail for two reasons.

And I would caution you against saving a little bit of time now (by condensing the tests) to pay for it later by spending a lot of time tracking down the coupling in your test or the ambiguity in your test failures.


问:
If your workmate is quitting his job, would you notify your boss?
If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>

答: Clue: Mind your own business.

Body: Clue: Mind your own business.


问:
Are a class's methods stored only once in memory?
When I create an instance of a class the system allocates memory for all instance variables of the class. Some languages may call them fields or properties.

But what about the code of the class methods? Are those duplicated too or do I have the code only once in memory? I know all instances got their own values - even inside the methods - but I would like to know about the code.

Do I have instance variables and separate "instance methods"?

答:
In layman's terms:

Methods are not part of the "state" of an object

They are part of the blueprint

They are part of the cookie cutter, not the dough

They belong to the class, not the instance

Hence I guess they are stored in memory once


答:
Do I have instance variables and separate "instance methods"?

Generally no. Methods belong to the class itself and look like C# extension methods under the hood:

```<code>void Foo(this T instance, param, param, param)
</code>```

so that x.Foo(a,b,c) really gets called like Foo(x,a,b,c). That said, certain languages/implementations allow replacing the methods, so can allocate space for a pointer to which Foo to use, but even in those cases the language makes those methods look like variables (since they effectively are variables).

Title: Are a class's methods stored only once in memory?

Body:
When I create an instance of a class the system allocates memory for all instance variables of the class. Some languages may call them fields or properties.

But what about the code of the class methods? Are those duplicated too or do I have the code only once in memory? I know all instances got their own values - even inside the methods - but I would like to know about the code.

Do I have instance variables and separate "instance methods"?

Body:
Do I have instance variables and separate "instance methods"?

Generally no. Methods belong to the class itself and look like C# extension methods under the hood:

void Foo(this T instance, param, param, param)

so that x.Foo(a,b,c) really gets called like Foo(x,a,b,c). That said, certain languages/implementations allow replacing the methods, so can allocate space for a pointer to which Foo to use, but even in those cases the language makes those methods look like variables (since they effectively are variables).


问:
Is RESTFUL API as back-end service one of the best (or suitable) choice for Mobile App?
I have a background on .NET development, recently I was asked to code back-end service for a mobile app. I had experiences on MVC, and now I'm trying to understand more on Restful Web API.

My questions are: Is Restful API as back-end service one of the best (or suitable) choice for mobile app? What is the common solution for mobile app back-end service nowadays?

Edit: (about off-topic)

I read this before I ask this question.

If it's related to higher level programming concepts or is conceptual
  (but still related to programming), it should be on Programmers.

This is not a question about recommend a tool, library or favorite off-site resource

I asked about

if restful web API suitable for creating mobile service

what are the common solutions to build mobile app API

答:
No. In my experience RESTful APIs and mobile apps aren't a natural fit.

Although there are a number of different views of what 'RESTful' actually means, one of the common themes throughout most people's view of RESTful is that the API should be stateless between calls. This is perhaps one of the few, agreed, defining features.

However, mobile apps are very prone to communications issues (think 3G flakey connections), and apart from endless retries of complete call/response messages, the only way to deal with this for efficient large data responses is to allow for partial responses and some kind of additional protocol implemented in the API to allow for partial results in chunks or blocks. This is especially true for APIs that have to synchronise large data sets. This isn't possible in a stateless, pure, RESTful API message structure.

Pure RESTful API message definitions wouldn't allow messages from the client like 'OK, I got the first 10K of data but i didn't get the whole response, can you send the remaining bit...'

So, implement a suitable message API between mobile client and server, but don't be a slave to 'RESTful' definitions or you'll be sacrificing good design for trendy techniques.


答:
Code is part of the static data associated with the class.

Typically eEach class has a function table that references the virtual (aka. overridable) functions and each object has a pointer to the function table of its instance class. So the collection of instance methods are coalesced into a single pointer in the object.

So when calling a method the compiler looks into the table of the object and finds the correct function.


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答: Knock on his door. Ask him if he has any shit jobs he's been putting off that you might be able to handle. Tell him to just fire you off an email later if he doesn't have time right now.</p>


问:
Loading database in memory vs querying
I am currently developing a continuous backup software. The key feature of the software is instant backup meaning that each time a file is created, modified, renamed or deleted the change is immediately reflected on the backup repository.

In order to achieve this we designed the system so that once the client application starts, the entire backed up files database is loaded in memory. The issue arise when backing up large amounts of files say 10 - 15 million files. This first causes the load time to be slow and high memory usage. In some cases reaching 2GB.

Querying the database on every change is also frowned upon as it will cause heavy loads on the disk where the database resides not to mention how slow the query execution time becomes as the database grows.

So I was wondering what options does one have to design such a system to be memory efficient and reasonably fast.

答:
The time taken to query a local database on disk should be orders of magnitude less than the time required to backup a file or communicate over the internet. (Your database isn't on the online server, is it? In which case keep a cached copy locally - assuming this isn't shared between users. Use a version number to check that the local host is using the same version of the database as the remote server).

I would expect some recency effects: after a file is created, it is quite likely to be updated or renamed. So if database access is still an issue, cache some of the recent entries...

Title: Loading database in memory vs querying


答:
This cannot be objectively answered without knowing the language.

Here are explanations for two languages which cover many of the generally important points.

C++

Typically, some code will be duplicated while other code will not. Inline functions will of course be duplicated, and this includes any code in the class declaration which is implicitly inline. Code that is defined separately will not be duplicated.

Template classes (e.g. STL containers) are normally duplicated since they normally have the declaration and definition combined (see previous point).

Linkers can perform their own optimizations to combine code like this, although in practice I do not believe this is common.

Without a JVM or CLR to monkey around with memory at run time, whatever is compiled is highly likely to be what is loaded in memory at run time.

Java

Byte code will not be duplicated (i.e. in .class files). Due to the nature of class files being able to be compiled and manipulated separately, there will be no duplication or optimization across classes. However, the JIT compiler is free to inline code at runtime, which would duplicate it in memory.

Sources: Java HotSpot VM Options - JRockit (there are quite a few references but very little official Oracle documentation on this topic)


答:
Loading the data to memory in a sane manner is the job of the database engine...

You DO NOT need to manually perform that task, your database  engine will perform that task for you, its purpose is to process queries and cache the required data.  Unless you are firing 1000's of queries a second, dont be afraid to fire multiple queries to a database, it is designed for it

Title: Loading database in memory vs querying

Body:
I am currently developing a continuous backup software. The key feature of the software is instant backup meaning that each time a file is created, modified, renamed or deleted the change is immediately reflected on the backup repository.

In order to achieve this we designed the system so that once the client application starts, the entire backed up files database is loaded in memory. The issue arise when backing up large amounts of files say 10 - 15 million files. This first causes the load time to be slow and high memory usage. In some cases reaching 2GB.

Querying the database on every change is also frowned upon as it will cause heavy loads on the disk where the database resides not to mention how slow the query execution time becomes as the database grows.

So I was wondering what options does one have to design such a system to be memory efficient and reasonably fast.


问:
Is it ok to restart a BackgroundWorker inside its Completed event
I want a background worker to continue running and occasionally update the user interface. My first idea was to use a BackgroundWorker and in its completed event just fire it up again.

Is using a BackgroundWorker in this fashion acceptable?  Or are there potential issues from using the completed event to trigger the worker?

Below is some Pseudo code of what my intentions are

```<code>class Program
{
    private static BackgroundWorker worker;
    private static Int32 runs = 0;

    static void Main(string[] args)
    {
        worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        worker.RunWorkerAsync(runs);
        Console.ReadLine();
    }

    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        //Do time consuming work
        Thread.Sleep(3000);
    }

    static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //Update the UI and start time consuming work again
        runs++;
        Console.WriteLine("Completed run #" + runs);
        worker.RunWorkerAsync();
    }
}
</code>```

答:
It's not absolutely clear from the spec whether a BackgroundWorker could be considered to be still running when the RunWorkerCompleted event is triggered - in which case calling RunWorkerAsync() will cause an exception.

Because the spec is unclear I wouldn't re-use the BackgroundWorker object: it might work or it might break on different releases of .Net. Just create a new one in the worker_RunWorkerCompleted() handler.

If you search for BackgroundWorker reuse, you will find several posts suggesting there might be some issues in this area.


问:
Microchip XC8: How to pack code against an upper limit?
I have a project for a PIC16F1454 that needs some custom linking.  Basically, I've separated my code into two parts that can be downloaded separately in the field and thus update (almost) all of the flash memory, including the bootloader.  As part of the plan to avoid bricking itself, I have this structure:

Lower, protected by hardware, not field-updateable:

Startup and image-copy code, written in assembly

Middle:

Application space

Also used to download new images

Upper:

Bootloader space

And there's some code in various places that enforces that structure.

The bootloader includes a USB stack, a main loop, and some helper functions that add up to slightly more than one page of flash, which causes some problems for the linker.  For example, the help file says that this option is supposed to concatenate the entire list and put it against the specified upper limit (note the negative address):

-L-pUSBCode=-1FFEh,USBConst,BootloaderCode,BootloaderConst

But when I do that, all four psects overlap, with the usual, unintended consequences.  I did this:

-L-aBootloader=1400h-17FFh,1800h-1FFDh -L-dBootloader=2 -L-pUSBCode=Bootloader -L-pUSBConst=Bootloader -L-pBootloaderCode=Bootloader -L-pBootloaderConst=Bootloader

which defines a class with 2-byte elements that crosses a page boundary at 1800h and puts all four psects in that class.  While they didn't overlap, I got a big hole next to the page boundary, big enough for several of the helper functions to fit in.

I could assign functions more granularly to more than four psects, and that would probably make things fit better, but I'd rather not make it any more complicated than I have to.  Someone else (could be me after a few months) is probably going to modify it later, and I don't expect him to be intimately familiar with the details.

How can I pack the entire bootloader section as tightly as possible into upper memory, accounting for the springboard to main() at 1FFEh-1FFFh, without requiring a future developer to change anything outside of the C source files?

答:
First off, have you looked into the Optimization on the XC8? It may require a paid license, but it could also get you down below a page, keeping you from having to have those extra bits dangling onto the next page. Another thing to note is that sometimes the X series compilers will do very, very strange things under optimization settings. Thoroughly test your product if you use optimization settings. You may very well find bugs. Remember that Microchip is in the Processor Business, not the Compiler Business. It shows.

Secondly, have you considered trying the C18 compiler to see if that will give you a smaller binary? I'm not positive it will work with your chip, but it produces slightly different binaries, which could end up being smaller than the one XC8 gives you.

Finally, you may have to just rewrite the code until the compiler spits out something smaller. I've had to do this a few times to get around page lengths myself, and while it's never pretty, it's almost always better than having to manually add data to the end of a page when installing another Binary.


答:
The compiler might inline your code, but the copy that makes is not passed around with the instance.  The copy is physically stored within the code of the call site.  Likewise templates create a duplicate copy (except for the substituted types) for each different type of template instantiated, but those are not passed around with the instance either.

Under certain circumstances the instance's memory will contain a function pointer, but I don't know any language implementations that store the actual instructions with the instance.  Even in languages where functions are first-class and conceptually you are doing something like returning a closure from another function, the executable instructions are stored statically, and you're just passing around a pointer to those instructions and whatever state you need in context.


问:
Functional Programming vs. OOP
I've heard a lot of talk about using functional languages such as Haskell as of late. What are some of the big differences, pros and cons of functional programming vs. object-oriented programming?</p>

答:
(This answer is adapted from an answer to a closed question at StackOverflow.)

One of the big differences between functional programming and object-oriented programming is that each one is better at a different kind of software evolution:

Object-oriented languages are good when you have a fixed set of operations on things, and as your code evolves, you primarily add new things.  This can be accomplished by adding new classes which implement existing methods, and the existing classes are left alone.

Functional languages are good when you have a fixed set of  things, and as your code evolves, you primarily add new operations on existing things. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone.

When evolution goes the wrong way, you have problems:

Adding a new operation to an object-oriented program may require editing many class definitions to add a new method.

Adding a new kind of thing to a functional program may require editing many function definitions to add a new case.

This problem has been well known for many years; in 1998, Phil Wadler dubbed it the "expression problem".  Although some researchers think that the expression problem can be addressed with such language features as mixins, a widely accepted solution has yet to hit the mainstream.

Title: Functional Programming vs. OOP


答:
In my humble opinion the answer is both Yes and No.

My current work experiences are dealing with a JavaScript front end (using ExtJS & Sencha Touch) and all my data connections are to a .Net Web API 2.0 RESTful back-end.  But my application is internal and so I do not have as much concerns for Security and Authentication & State, plus I am hosting these small tidbit components within SharePoint (God forbid!!) and they are compartmentalized.  So a Web API 2.0 RESTful back-end for my CRUD works fantastically!

But I can totally see David Scholefield's points also.  You are asking a very broad apples to Oranges to Kitchen Sink kind of question.  In the end you want to do some deep dive Requirements gathering and compare the needs and Pros & cons, because as everyone knows, every project is slightly different.

Title: Is RESTFUL API as back-end service one of the best (or suitable) choice for Mobile App?

Body:
I have a background on .NET development, recently I was asked to code back-end service for a mobile app. I had experiences on MVC, and now I'm trying to understand more on Restful Web API.

My questions are: Is Restful API as back-end service one of the best (or suitable) choice for mobile app? What is the common solution for mobile app back-end service nowadays?

Edit: (about off-topic)

I read this before I ask this question.

If it's related to higher level programming concepts or is conceptual
  (but still related to programming), it should be on Programmers.

This is not a question about recommend a tool, library or favorite off-site resource

I asked about

if restful web API suitable for creating mobile service

what are the common solutions to build mobile app API


问:
Are C static libraries frowned upon?
There are 2 arguments for having shared libraries:

It helps reduce disk space.

When a shared library is updated, all the binaries depending on it get the update.

There is mainly one drawback for shared libraries:

They (can) introduce dependency hell.

On desktop computers, the 1st advantage doesn't really hold anymore. Wasting disk space isn't much of an issue these days.

Having static binaries would allow us to get way better package managers -- I mean, the dependency hell would be a thing of the past. Adding a program would be just adding a binary; eventually a folder to let it handle its files. Deleting a program would be simply deleting this file. Dependencies? Gone.

The 2nd advantage still stands, but I think the advantage of static binaries on desktop computers outweighs it. I mean, even new languages like Go compile all their binaries in spite of the shared libraries advantages, because of the convenience.

Since one of the main advantages of shared libraries is not a big deal anymore, are C static libraries are still frowned upon? If so, why?

答:
The premise of your question is flawed. What is frowned upon is sticking to doctrinaires and absolutes with no understanding of the basis behind them (Cargo Cult Programming ?).

The linked SO answer is an interesting study in that very topic- the Question was about why a compile with -static option was not working, the answer you linked to was nothing more than a rant about not using static linking. If does not discuss why its bad, and demands the OP uses dynamic linking. Its unfortunate it is marked as the correct answer (the answer following has twice as many votes and is the correct answer to the OP's question) because although the correct answer is there, its deeply hidden in amongst a dogmatic opinion.

The real question is what are the pros and cons of static vs dynamic linking and when would one be preferred over the other.

Title: Are C static libraries frowned upon?


答:
From a developer point of view, dynamic linking can often speed up your compile/link/test loop considerably.

From a package management point of view, take libGL, for example.  I have approximately a dozen different implementations of it available in my package manager, some generic and some targeting specific graphics cards.  If it wasn't dynamically linked, there would have to be a dozen versions of each program that links with libGL, or else you would have to devise an additional layer of abstraction that isn't as efficient as a function call.

Think of a security issue in a popular library like Qt.  With dynamic linking, I can just update that one package, instead of having to identify, recompile, and deploy every single package that links in Qt.

Static linking may have advantages in independently-deployed closed source applications, but in open source package management it hurts more than it helps.

Title: Are C static libraries frowned upon?

Body:
There are 2 arguments for having shared libraries:

It helps reduce disk space.

When a shared library is updated, all the binaries depending on it get the update.

There is mainly one drawback for shared libraries:

They (can) introduce dependency hell.

On desktop computers, the 1st advantage doesn't really hold anymore. Wasting disk space isn't much of an issue these days.

Having static binaries would allow us to get way better package managers -- I mean, the dependency hell would be a thing of the past. Adding a program would be just adding a binary; eventually a folder to let it handle its files. Deleting a program would be simply deleting this file. Dependencies? Gone.

The 2nd advantage still stands, but I think the advantage of static binaries on desktop computers outweighs it. I mean, even new languages like Go compile all their binaries in spite of the shared libraries advantages, because of the convenience.

Since one of the main advantages of shared libraries is not a big deal anymore, are C static libraries are still frowned upon? If so, why?


答:
I agree with mattnz's last point: this question is a loaded question. It assumes that static linking is bad. I can think of two reasons why this is not the case:

Static linking is safe: if a shared library is updated such that an application uses the new one (maybe the new overwrites the old, or the old one is removed), it can introduce risk that the new version breaks the application. This is a code change outside the scope of an official update for the application. It may not have been tested. Static linking sidesteps this by not sharing libraries externally. I hold that this is a disadvantage to shared libraries due to this risk. What if a new version of a shared library introduces a new bug that breaks certain older applications?

Static linking ensures an application is more self-contained. While shared libraries can be colocated with the primary executable, often they are deposited in shared locations. Statically linked applications are easier to ensure "portable" in the sense of "not requiring changes to files, directories or settings owned by the OS" (think Windows directory, registry, /etc).

Title: Are C static libraries frowned upon?


答: Node.js uses the V8 engine, which is a pure compiler. It never interprets. There isn't even an interpreter in V8, just two compilers.


问:
Wpf: Event driven vs MVVM design pattern
I'm a beginning coder and I've been working on a WPF app for several months now and struggled to implement anything in MVVM due to time constraits to learn so I coded my program the only way to knew how: with code behind, tight coupling, and a whole bunch of spaghetti code.

My program has grown into 20,000+ lines of messy (but working) code that is mostly event driven. The app I am building will probably be used and continue to be developed for years to come, but I will be the only one working on the code.

However, now that I have time to start learning MVVM, I'm wondering how useful it really is to follow the MVVM pattern. I'm considering refactoring my code into the MVVM pattern but everything seems 100x difficult to do with little documentation. With using code behind and tight coupling, I can make the UI do exactly what I want it to do and everything seems like it can be coded so much faster through the event-driven methods.

How important is it to follow the MVVM design pattern for WPF apps, especially in the long run? Do you think it's a good idea for me to invest my time to redesigning this app and following an MVVM pattern?

答:
It looks like you've found yourself in perfect learning situation.  Currently your application works, and I'm sure you're very familiar with all of the 20k lines of code.  Making changes isn't that difficult, and, so far, there doesn't seem to be any reason to change your development approach.

You are a cowboy!  And being a cowboy is a lot of fun!

But being a cowboy is a lot of work, and even the best cowboys run out of steam after a while (sorry about the mixed metaphors).

In the question you mentioned that the app will be used and maintained for years to come.  Those 20k lines will surely increase, and with every new feature you add, and every new bug you squish, you'll notice that it gets harder and harder to write code without breaking existing functionality.  This is tightly coupled spaghetti hell!

MVVM as a pattern encourages developers to loosely couple their code.  In the MVVM world you keep your Model separate from your view state (View Model) and display logic (View).  This does require a bit more up-front work, but the downstream benefits are many:

Unit testing your Model is easier.  No View baloney to worry about.

Integration testing your View Model is a breeze

Because your M, VM, and V are distinct sections of code, modifying one has a near 0% chance of causing regressions in the others.

And there are at least 7 other reasons.

But the most important reason to switch to MVVM over CBV (Cowboy View) is this:  You're human.  While humans are actually pretty good at creating mental models of complex things like software, doing so is a very draining endeavour.  And keeping track of frequently changing and ever growing software is a recipe for mental illness.

We are flawed sacks of flesh.  But fret not, for we are also organised flawed sacks of flesh.

By organising your code into classes with single responsibilities (eg, a ViewModel) you can now work on subsets of your application without having to load up your mental model of the entire application.  Your brain will thank you for this!

But don't take my word for it.  Like I said at the beginning of this pseudo-rant:  You're in a perfect learning situation.  You've made a classic mistake (there's no shame in that) and you're going to be around long enough for it to catch up to you.

Switch to MVVM now if you want.  Or don't.  Either way, you're going to eventually learn why it's a useful pattern.

My recommendation:  try to maintain your cowboy spaghetti for as long as you can.  The best way to learn is by making mistakes.  So make your big ones early and often!

Have fun!


问:
How is it possible that facial recognition software can work, but a reCAPTCHA can't be solved by a computer
If software can be built to recognize faces and match those faces to names, then how is that CAPTCHA works? Recognizing letters seems a lot easier than matching faces.  </p>

答:
Captcha doesn't always work; hackers use ever more sophisticated techniques to try and defeat it.  In response, Captcha systems distort the letters in some way to confound those techniques, either by twisting the letters, putting a line through them, reversing the background and foreground colors randomly, and so on.

This relies on the human's ability to still read the words in the presence of a lot of noise, a quality most OCR algorithms do not have.

In other words, Captcha works because we can obfuscate it in ways that makes it difficult for a computer to solve.  The same principle applies to any sort of computing security apparatus: we seek to find ways to secure content that are easy for humans to use, but hard for computers to reverse-engineer.  We are not always 100 percent successful in that regard.

Facial recognition doesn't always work either.  Despite the implication in your question that computers are better at it, the same problems that face Captcha solving algorithms also apply to facial recognition software: you still need a good candidate image, the process can be confounded by shadows, etc.

Note that Captchas don't have to be perfect.  The most trivial of Captchas still eliminate 90 to 95 percent of the spammers; the good ones eliminate 99 percent.  It's not about keeping everyone out; it's about closing the door so that not any Tom, Dick or Harry can just walk through the doorway without some sort of challenge.

Ultimately, most spammers are lazy, and aren't really in the business of writing sophisticated software algorithms to defeat Captcha's, unless the potential payoff is especially great.  They're after the low-hanging fruit.

ContentLicense: CC BY-SA 4.0


答:
It all comes down to recognizing patterns. Facial recognition works by recognizing patterns (distance ratios) of facial features, as well as shadows.  These ratios are looked up in a database to try and match an actual face - this isn't flawless however and can bring up false positives.

CAPTCHAs and reCAPTCHAs use distortions to muddle recognizable patterns of letters and numbers, to make it difficult for OCR algorithms to understand them.

Title: How is it possible that facial recognition software can work, but a reCAPTCHA can't be solved by a computer

Body: If software can be built to recognize faces and match those faces to names, then how is that CAPTCHA works? Recognizing letters seems a lot easier than matching faces.  </p>


答:
How much scaffolding your Selenium UI tests require or how long it takes to run them are genuine practical factors. You might rationally segment such tests into an "beyond unit test" suite. Just don't eliminate that testing step "because it isn't a unit test." If you're working toward software quality, you can't be "saved by the bell" of what makes a pure unit test or not.

A traditional response would be: Well, you need to add in other testing layers (module, integration, specification, acceptance, ...) and test those things as well--but that's outside the scope of pure unit testing. But that distinction is often used to punt on doing those other forms of testing, or leave it to someone else. "Not my job, man. I'm just responsible for unit tests. Someone else is responsible for integration and UI testing." That punting is an abdication of responsibility, and inimical to TDD's philosophy of integrating coding and testing. It's also a big reason unit tests are infamous for passing with flying colors, even when the code as a whole is still breaking or not doing the job it was designed to do.

There is a place for segmenting testing realms. Performance testing, walk-through-the-UI testing, intrusion testing, and exhaustive compliance testing against all possible supported libraries and platforms can each require spinning up considerable middleware and virtual instances, and might take dekaminutes or hours to complete. Run those test suites occasionally, rather than every code edit. But for goodness sake do not use their "higher level" nature to avoid doing them.

There is also often a notion that integration, UI, and other forms of testing require different tools. While you may need some additional tools (Selenium, in this case), but I cannot see the point in requiring an entirely different testing foundation of test runners, fixtures, mocking and support libraries, and so on. I'd argue that having different infrastructure for 4 or 5 desired layers of testing is anti-simplicity and ultimately itself an anti-pattern.

My experience is that rigid conformance to unit testing dogma--"only one possible reason to fail" and "don't test things together" e.g.--is restrictive and ultimately counter-productive. You certainly want tests to exercise your code in the clear, simple, direct ways. Pure unit tests can and do help with that. But why stop there?

I build "unit" tests with an expanded model of what constitutes a unit--not just individual software atoms or particles, but multiple routines and objects, acting together. Atoms composed into molecules, and then molecules composed into larger molecules.

Relaxing the notion of what constitutes a "unit" and piggybacking unit testing infrastructure for integration and UI tests may not win me awards for testing purity, but it helps larger requirements. It gets more tests written and executed--both in an absolute sense, and per hour of testing effort. And it gets a wider swath of my code tested, in ways that mimic real use.

Isn't that the ultimate goal? Having more robustly-tested, works-together, quality software products? If so, go ahead and use a pure, no-dependencies-whatever model of unit testing to start. Just don't stop there. That slightly higher-level or as-seen-by-a-user tests might fail in several ways, or that they have dependencies--that may be a reason to put those tests into different test specs/files, or to run them less frequently. But it's not a reason to skip them--and often, not even a reason to decouple them from the basic coding process.

Title: Is it anti-pattern to mix unit test and web test?

Body:
It is a language agnostic question, e.g. I have a unit test like

```<code># Unit test
User user = User.create('john');
assertEquals("User name is john", "john", user.getName());

# Web test start from here
goTo("/user/john");
assertTitleEquals("john");
</code>```

Do you think it is an anti-pattern?
Although I can write a full selenium test suites to do the same thing, but using the above code save much of my time (e.g. no more click('Login'); waitUntil etc, and I don't need to worry if my UI is changed at all, sound like it is a quick and more stable approach to test?


问:
Programming by usage
Iv'e been programming for 15 years now and I often read online that it seems like a lot of people will plan out their objects and how they interact and the data they need and that seems to shape the exposed interface. However, I find my brain works from usage backwards to the structure and data. I'm wondering if this is common and any pros/cons to this approach that anyone can think of, and what your mindset is when a new task is thrown your way. I want explore other ideas and approaches in mindset but I only know my mindset and I've been doing it so long. Is this what everyone does?

For example if I were to be tasked with making a stapler class I would write the usage that would make sense to me first and how I would want to use it and then fill in that usage. The first thing I do is open up notepad++ and type:

```<code>Stapler stapler = new Stapler(200);

stapler.Load(200);
stapler.Staple(papers);
stapler.UnJam();
int stapleCount = stapler.StaplerCount;
</code>```

By looking at this it tells me that my stapler needs these functions/properties and I can infer what the parameters are by looking at them most of the time.

I seem to have an easier time thinking in code usage like this vs thinking about an abstract object and all it's functionality before writing any code. Writing out the usage often makes the abstract object real in my mind and is easier for me to grasp.

答: Isn't your "usage" really just another form of use cases because your usage prototype, basically does what uses cases does which models the usage of objects. In that form, I think a lot of people make use case diagrams. Use-case diagrams derive from specifications document. So I guess that is within the planning process for objects. Only my perspective, however. I noticed it and wanted to chime in.</p>

Title: Programming by usage


问:
Where is the 'this' variable stored?
Let's take this simple c++ program as an example:

```<code>#include <vector>
class A
{
  void fun() { a = this + 1; }
  A* a;
};

main()
{
  std::vector<A> vec;
  vec.resize(100);
}
</code>```

Forgetting for the moment that this is a pointer to some instantiation of A, this question is about the variable this itself, and where its contents (the value of the memory address) is stored.

It can't be a literal because the compiler can't know the location of class A, so its contents must be allocated somewhere on the stack or heap as a variable. In this case the instances of A are allocated on the heap; does this mean the this pointer is also on the heap?

Looking at the resize call of vec, a compiler might do something like this under the hood:

```<code>std::vector<A>::resize(this, 100); // where 'this' is a pointer to vec
</code>```

So my question is, where does the this pointer come from? Ie. where is the contents of this (the 32/64-bit memory address value) stored in memory for it to be passed to this method?

I would presume it can't be a normal member; so my first thought was that it's a mangled global variable of some sort, but then by storing an unknown number of them in a vector I don't see how the compiler could achieve this either. Where is the contentx of the this variable stored in relation to the contents of the A class member to which it refers?

If the standard has something to say about this, I would prefer an answer with reference to the standard.

Note that the reason I want to know is because I am concerned about false sharing of the memory allocated for the this object if I modify member variables. Knowledge of where the this object is stored might affect padding decisions.

答:
The pointer this is not stored anywhere in relation to the class instance (because if you already have the class instance, getting its pointer is trivial!). Rather it behaves like a hidden argument that is always implicitly passed into member functions such as resize. (In some languages like Python this is passed explicitly.)

Note that the standard says nothing about where this is stored. You aren't allowed to take the address of this because it's not a variable. Hence your question concerns entirely an implementation detail.

As a concrete example,

```<code>class A
{
public:
  void fun(int x) { a = this + x; }
  A* a;
};

void foo(A& a)
{
  a.fun(1);
}
</code>```

This is semantically equivalent to the following:

```<code>struct A
{
  A* a;
};
void A_fun(A* _this, int x) { _this->a = _this + x; }

void foo(A& a)
{
  A_fun(&a, 1);
}
</code>```

So it is possible for a compiler to implement member functions in this way (or something similar).  How an actual compiler implements it will vary, however.

Title: Where is the 'this' variable stored?

Body:
The pointer this is not stored anywhere in relation to the class instance (because if you already have the class instance, getting its pointer is trivial!). Rather it behaves like a hidden argument that is always implicitly passed into member functions such as resize. (In some languages like Python this is passed explicitly.)

Note that the standard says nothing about where this is stored. You aren't allowed to take the address of this because it's not a variable. Hence your question concerns entirely an implementation detail.

As a concrete example,

class A
{
public:
  void fun(int x) { a = this + x; }
  A* a;
};

void foo(A& a)
{
  a.fun(1);
}

This is semantically equivalent to the following:

struct A
{
  A* a;
};
void A_fun(A* _this, int x) { _this->a = _this + x; }

void foo(A& a)
{
  A_fun(&a, 1);
}

So it is possible for a compiler to implement member functions in this way (or something similar).  How an actual compiler implements it will vary, however.


答: It depends on the calling convention of the compiler but usually it's passed as the first (hidden) argument and not stored in A anywhere. The first argument is then either passed as i a register or on the stack.</p>

Title: Where is the 'this' variable stored?

Body:
Let's take this simple c++ program as an example:

```<code>#include <vector>
class A
{
  void fun() { a = this + 1; }
  A* a;
};

main()
{
  std::vector<A> vec;
  vec.resize(100);
}
</code>```

Forgetting for the moment that this is a pointer to some instantiation of A, this question is about the variable this itself, and where its contents (the value of the memory address) is stored.

It can't be a literal because the compiler can't know the location of class A, so its contents must be allocated somewhere on the stack or heap as a variable. In this case the instances of A are allocated on the heap; does this mean the this pointer is also on the heap?

Looking at the resize call of vec, a compiler might do something like this under the hood:

```<code>std::vector<A>::resize(this, 100); // where 'this' is a pointer to vec
</code>```

So my question is, where does the this pointer come from? Ie. where is the contents of this (the 32/64-bit memory address value) stored in memory for it to be passed to this method?

I would presume it can't be a normal member; so my first thought was that it's a mangled global variable of some sort, but then by storing an unknown number of them in a vector I don't see how the compiler could achieve this either. Where is the contentx of the this variable stored in relation to the contents of the A class member to which it refers?

If the standard has something to say about this, I would prefer an answer with reference to the standard.

Note that the reason I want to know is because I am concerned about false sharing of the memory allocated for the this object if I modify member variables. Knowledge of where the this object is stored might affect padding decisions.


问:
Long Keywords like `function` and `namespace`
In many English-based programming languages like C++ and JavaScript, there exist long keywords like function, namespace, exception (in OCaml languages) and such. Do you think shorter keywords like func should replace them? Why or why not? What about replacing them with digraph operators?

The long keywords we will be mainly talking about, but not limited to, are mainly from curly-brace imperative languages: function, namespace, implements, instanceof and synchronized (I always misspell that).
You should also show the examples from your favourite programming language.

答: Keywords are chosen so as to reduce ambiguity while using them. Also to make the program easier to read. That's why even for a non programmer, the code makes a bit of sense.</p>


答:
Shared libraries are strongly preferred by Linux distribution maintainers for basically your reason #2.  It's really important to them that, for instance, when someone finds a security bug in zlib, they don't have to recompile every single one of the programs that uses zlib---not only would it cost them more CPU cycles to do the recompiling, everyone who uses the distro would then have to re-download all of those programs.  Meantime, within the set of packages provided by a distribution, dependency hell is not an issue, because everything is tested to work with that set of libraries.

If you're building third-party software that needs libraries that aren't in your distribution, then statically linking those libraries may be less hassle than the alternative, and that's fine.

The other important thing to know is that GNU libc and GCC's libstdc++ both have components that don't work reliably if the library is statically linked.  The most common problem is with dlopen, because whatever module you load with dlopen is itself dynamically linked with libc.so.6.  So that means now you have two copies of the C library in your address space, and hilarity ensues when they don't agree on which copy of the internal malloc data structure (for instance) is authoritative.  It gets worse: a whole bunch of functions that don't appear to have anything to do with dlopen, like gethostbyname and iconv, use dlopen internally (so that their behavior is runtime-configurable).  Fortunately, the ABI for libc and libstdc++ is very stable, so you are unlikely to encounter problems dynamically linking them.

Title: Are C static libraries frowned upon?


答:
It sounds like you want to know where the contents of an instance of the class are stored. The answer is, it depends.

Classes can be instantiated on the stack, on the heap, or indirectly on the heap as in your vector example.

In your vector example, following the vec.resize(100), there are 100 instances of class A constructed in the memory reserved by the vector vec. The memory for the vector vec is allocated on the heap. Hence, the instances of a are indirectly stored in the heap.

About this

this is quite simply the address of an instance of the class. There can be many instances of a class. In your example, there are 100 instances of class A, each with their own this. The this for an instance is not stored anywhere. It is just the address of the instance.

For example, call vec[3].fun(), and the a member of the instance of class A at the third location of vector vec will be a pointer to the instance of class A at the fourth location of vector vec. (Of course, you can in turn, call fun() using the member variable a.)

The value of this, within a method call is determined by the caller of the method. The pointer to the instance at the time of the method call becomes the this pointer to the method call.

Title: Where is the 'this' variable stored?


答:
Static and dynamic libraries each have their own uses. Looking at a single application in scope we get a different idea about what is necessary and what isn't.

Static linking drastically simplifies application deployment. Not having to detect and deal with different versions.  Just bake and deploy.

The obvious advantage with dynamic libraries is the ability to apply updates independently.

This is one of the reasons I loathe maven and other similar dynamic linking project builders for java. They expect a single library version to be available at a given url forever and ever. Not understanding the problem that occurs in 10 years when no one can compile the application because all the source and jars are gone.

Title: Are C static libraries frowned upon?


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答: Sometimes I've been so clever that I've been wrong.</p>


问:
Repurpose MySQL as a mutex
My application needs to perform an operation once every 10 minutes, but that operation is triggered many times more frequently. Occasionally it is triggered three or four times a second in different processes, and that's the main thing I want to avoid.

It's Django, and at first I used the django.core.cache feature, but I am still getting more than one worker performing the operation simultaneously.

I have Redis also, and know that WATCH and MULTI can be used to prevent race conditions, but the django-redis library doesn't support them.

This is my solution; please comment on how well (or not) it prevents multiple workers (processes) from performing the operation simultaneously:

Have a MySQL table with fields when and uuid and just a single row starting with both NULLs.

When a worker is told to start the operation, it quits early if when is less than 10 minutes ago.

Otherwise, generate a UUID and store it in the table, updating when to NOW() in the same query.

Then, select the row and quit early if uuid doesn't match the one just generated.

Otherwise continue with the operation

This relies on MySQL enforcing the order of reads and writes and enforcing that only one query access the row at once, which may be invalid assumptions.

Any alternative ways of keeping Celery processes from running a task simultaneously would be just as helpful.

答:
So, my understanding is

this operation is triggered by activity within the application

the triggering activity may occur up to several times per second

although the operation is triggered many times per second it should only   execute once every ten minutes.

A one-column table would suffice:

```<code>create table Mutex (LastExecuted datetime NOT NULL);
insert Mutex(LastExecuted) values ('2010-01-01');
</code>```

Initialise the column to an arbitrary value at least 10 minutes in the past.  Initialising to NULL will introduce a special case for the first execution which will have to be coded for.

A worker can grab rights to perform work by trying to update this value

```<code>update Mutex
set LastExecuted = NOW()
where LastExecuted < DATE_SUB(NOW(), INTERVAL 10 MINUTE);
</code>```

Capture the number of rows affected by this statement.  If the statement affects zero rows then 10 minutes have not passed.  If it affects 1 row, the current worker has acquired the mutex and should perform the operation.  If it affects more than 1 row you have a problem with your application!

This will also provide protection from a worker grabbing the mutex then terminating.  After 10 minutes another worker will be able to grab the right to do work.

Title: Repurpose MySQL as a mutex

Body:
So, my understanding is

this operation is triggered by activity within the application

the triggering activity may occur up to several times per second

although the operation is triggered many times per second it should only   execute once every ten minutes.

A one-column table would suffice:

create table Mutex (LastExecuted datetime NOT NULL);
insert Mutex(LastExecuted) values ('2010-01-01');

Initialise the column to an arbitrary value at least 10 minutes in the past.  Initialising to NULL will introduce a special case for the first execution which will have to be coded for.

A worker can grab rights to perform work by trying to update this value

update Mutex
set LastExecuted = NOW()
where LastExecuted < DATE_SUB(NOW(), INTERVAL 10 MINUTE);

Capture the number of rows affected by this statement.  If the statement affects zero rows then 10 minutes have not passed.  If it affects 1 row, the current worker has acquired the mutex and should perform the operation.  If it affects more than 1 row you have a problem with your application!

This will also provide protection from a worker grabbing the mutex then terminating.  After 10 minutes another worker will be able to grab the right to do work.


答:
Annotating your example:

```<code>main()
{
  std::vector<A> vec;
  vec.resize(100); // What really happens: vec.resize(&vec, 100);
}
</code>```

The compiler emits code that calculates the address of the class instance vec and passes it as the first parameter to any method call against that instance. There is no global variable 'this'. There is no member variable 'this', there is just an address passed as a formal parameter to a method call. You can refer to it in your method body just like any other parameter.

Title: Where is the 'this' variable stored?

Body:
Annotating your example:

main()
{
  std::vector<A> vec;
  vec.resize(100); // What really happens: vec.resize(&vec, 100);
}

The compiler emits code that calculates the address of the class instance vec and passes it as the first parameter to any method call against that instance. There is no global variable 'this'. There is no member variable 'this', there is just an address passed as a formal parameter to a method call. You can refer to it in your method body just like any other parameter.


答:
Truth be told that there are various ways that a compiler can implement this, and it shouldn't matter to you which one is actually used. Yes, there may be some subtle interactions with the processor that would impact performance but the compiler writers almost certainly know about it way better than you do.

But the simplest approach is to simply treat this like it was any other parameter. So for a class like:

```<code>class Foo
{
    void bar();
    ...
};

Foo foo;
foo.bar();
</code>```

The code that is produced is probably pretty much the same as the C equivalent of:

```<code>struct Foo
{
    ...
}

Foo_bar(Foo * foo) {
}

Foo foo;
Foo_bar(&foo);
</code>```

So inside Foo::bar, this simply comes from being a hidden parameter to the method. In that respect, it works just like any other parameter.

However, you might want to know, where does the pointer come from in the first place? At some point in time the Foo object was created. It may have been created as a local variable, or perhaps via new. In either case, the program starts the creation of Foo by selecting the piece of memory to create the object in. It knows the correct address of Foo, because it selected or was given the piece of memory to put Foo into. It simply keeps track of that address for when it needs that pointer later.

Title: Where is the 'this' variable stored?

Body:
Truth be told that there are various ways that a compiler can implement this, and it shouldn't matter to you which one is actually used. Yes, there may be some subtle interactions with the processor that would impact performance but the compiler writers almost certainly know about it way better than you do.

But the simplest approach is to simply treat this like it was any other parameter. So for a class like:

class Foo
{
    void bar();
    ...
};

Foo foo;
foo.bar();

The code that is produced is probably pretty much the same as the C equivalent of:

struct Foo
{
    ...
}

Foo_bar(Foo * foo) {
}

Foo foo;
Foo_bar(&foo);

So inside Foo::bar, this simply comes from being a hidden parameter to the method. In that respect, it works just like any other parameter.

However, you might want to know, where does the pointer come from in the first place? At some point in time the Foo object was created. It may have been created as a local variable, or perhaps via new. In either case, the program starts the creation of Foo by selecting the piece of memory to create the object in. It knows the correct address of Foo, because it selected or was given the piece of memory to put Foo into. It simply keeps track of that address for when it needs that pointer later.


答:
The point is that this is an implicit formal parameter (containing the address of the object whose method you are calling). It is not a local variable.

Look at the generated code of your program. I compiled (on Linux/Debian/Sid/x86-64 with GCC 4.9.1) your example arman.cc with

```<code>  gcc -O1 -fverbose-asm -S arman.cc
</code>```

and got the function main below

```<code>         .globl  main
         .type   main, @function
 main:
 .LFB512:
         .cfi_startproc
         .cfi_personality 0x3,__gxx_personality_v0
         .cfi_lsda 0x3,.LLSDA512
         pushq   %rbx    #
         .cfi_def_cfa_offset 16
         .cfi_offset 3, -16
         subq    $48, %rsp       #,
         .cfi_def_cfa_offset 64
         movq    $0, 16(%rsp)    #, MEM[(struct _Vector_impl *)&vec]._M_start
         movq    $0, 24(%rsp)    #, MEM[(struct _Vector_impl *)&vec]._M_finish
         movq    $0, 32(%rsp)    #, MEM[(struct _Vector_impl *)&vec]._M_end_of_storage
         movq    $0, (%rsp)      #, MEM[(struct A *)&__x]
         movq    %rsp, %rcx      #,
         movl    $100, %edx      #,
         movl    $0, %esi        #,
         leaq    16(%rsp), %rdi  #, tmp92
 .LEHB0:
         call    _ZNSt6vectorI1ASaIS0_EE14_M_fill_insertEN9__gnu_cxx17__normal_iteratorIPS0_S2_EEmRKS0_  #
 .LEHE0:
         movq    16(%rsp), %rdi  # MEM[(struct _Vector_base *)&vec]._M_impl._M_start, D.10014
         testq   %rdi, %rdi      # D.10014
         je      .L34    #,
         call    _ZdlPv  #
         jmp     .L34    #
 .L33:
         movq    %rax, %rbx      #, tmp91
         movq    16(%rsp), %rdi  # MEM[(struct _Vector_base *)&vec]._M_impl._M_start, D.10014
         testq   %rdi, %rdi      # D.10014
         je      .L32    #,
         call    _ZdlPv  #
 .L32:
         movq    %rbx, %rdi      # tmp91,
 .LEHB1:
         call    _Unwind_Resume  #
 .LEHE1:
 .L34:
         movl    $0, %eax        #,
         addq    $48, %rsp       #,
         .cfi_def_cfa_offset 16
         popq    %rbx    #
         .cfi_def_cfa_offset 8
         ret
         .cfi_endproc
</code>```

You see that some space for your vec is allocated on the stack (e.g. with subq $48, %rsp etc...) and then the address of that zone on the stack is passed as the this formal argument (using the usual x86-64 ABI conventions, which dictates (p 20) that the first argument of function is passed thru register %rdi) so you could say that this is, at the beginning of some member function, in the register %rdi ...

IIRC, the wording of the C++ standard are vague enough to permit the this argument to be passed in a special way, but all the ABIs I heard of are passing it exactly as the first (pointer) argument of usual C functions.

BTW, you should trust the compiler and let it pass this as convenient and as prescribed by ABI specifications.

Title: Where is the 'this' variable stored?

Body:
The point is that this is an implicit formal parameter (containing the address of the object whose method you are calling). It is not a local variable.

Look at the generated code of your program. I compiled (on Linux/Debian/Sid/x86-64 with GCC 4.9.1) your example arman.cc with

  gcc -O1 -fverbose-asm -S arman.cc

and got the function main below

         .globl  main
         .type   main, @function
 main:
 .LFB512:
         .cfi_startproc
         .cfi_personality 0x3,__gxx_personality_v0
         .cfi_lsda 0x3,.LLSDA512
         pushq   %rbx    #
         .cfi_def_cfa_offset 16
         .cfi_offset 3, -16
         subq    $48, %rsp       #,
         .cfi_def_cfa_offset 64
         movq    $0, 16(%rsp)    #, MEM[(struct _Vector_impl *)&vec]._M_start
         movq    $0, 24(%rsp)    #, MEM[(struct _Vector_impl *)&vec]._M_finish
         movq    $0, 32(%rsp)    #, MEM[(struct _Vector_impl *)&vec]._M_end_of_storage
         movq    $0, (%rsp)      #, MEM[(struct A *)&__x]
         movq    %rsp, %rcx      #,
         movl    $100, %edx      #,
         movl    $0, %esi        #,
         leaq    16(%rsp), %rdi  #, tmp92
 .LEHB0:
         call    _ZNSt6vectorI1ASaIS0_EE14_M_fill_insertEN9__gnu_cxx17__normal_iteratorIPS0_S2_EEmRKS0_  #
 .LEHE0:
         movq    16(%rsp), %rdi  # MEM[(struct _Vector_base *)&vec]._M_impl._M_start, D.10014
         testq   %rdi, %rdi      # D.10014
         je      .L34    #,
         call    _ZdlPv  #
         jmp     .L34    #
 .L33:
         movq    %rax, %rbx      #, tmp91
         movq    16(%rsp), %rdi  # MEM[(struct _Vector_base *)&vec]._M_impl._M_start, D.10014
         testq   %rdi, %rdi      # D.10014
         je      .L32    #,
         call    _ZdlPv  #
 .L32:
         movq    %rbx, %rdi      # tmp91,
 .LEHB1:
         call    _Unwind_Resume  #
 .LEHE1:
 .L34:
         movl    $0, %eax        #,
         addq    $48, %rsp       #,
         .cfi_def_cfa_offset 16
         popq    %rbx    #
         .cfi_def_cfa_offset 8
         ret
         .cfi_endproc

You see that some space for your vec is allocated on the stack (e.g. with subq $48, %rsp etc...) and then the address of that zone on the stack is passed as the this formal argument (using the usual x86-64 ABI conventions, which dictates (p 20) that the first argument of function is passed thru register %rdi) so you could say that this is, at the beginning of some member function, in the register %rdi ...

IIRC, the wording of the C++ standard are vague enough to permit the this argument to be passed in a special way, but all the ABIs I heard of are passing it exactly as the first (pointer) argument of usual C functions.

BTW, you should trust the compiler and let it pass this as convenient and as prescribed by ABI specifications.


问:
Uniqueness of for loop
How does the for loop function is implemented so that it can accept ; as parameter separator rather than , which is trivial in normal functions.

答:
The for loop is not a function, the for_each is http://en.cppreference.com/w/cpp/algorithm/for_each which takes , as parameter separator.

for is a statement, according to the C++ standard §6.5.3.

You can look at a for as a set of actions being performed, like this: for(initialization; condition; expression) at which point they really aren't different parameters, but different statements.

Title: Uniqueness of for loop


答:
This is a non-issue thanks to the auto-complete capabilities of any text editor worth programming in.  You can make a keyword named FunctionNamespaceImplementsInstanceOfSynchronized for all I care.

I'll just hit tab.

One other thing... I don't think I've ever in my programming career come across a keyword that was long enough to annoy me.  The examples you give aren't exactly striking fear into my fingers.

However, I really hate those damn double underscores in python.

Title: Long Keywords like `function` and `namespace`

Body:
In many English-based programming languages like C++ and JavaScript, there exist long keywords like function, namespace, exception (in OCaml languages) and such. Do you think shorter keywords like func should replace them? Why or why not? What about replacing them with digraph operators?

The long keywords we will be mainly talking about, but not limited to, are mainly from curly-brace imperative languages: function, namespace, implements, instanceof and synchronized (I always misspell that).
You should also show the examples from your favourite programming language.


问:
Does an Rcpp-dependent package require a GPL license?
I'm writing a commercial package that uses R (GPL) for its computation. The GPL FAQ clearly states that GPLed programming language interpreters do not impose licensing restrictions on the "program" (text file with R code). So far, so good.

Part of the package is compiled using Rcpp, which also uses the GPL. The next paragraph in the FAQ reads:

However, when the interpreter is extended to provide "bindings" to other facilities (often, but not necessarily, libraries), the interpreted program is effectively linked to the facilities it uses through these bindings.

It can be interpreted that R is providing a binding to the Rcpp libraries (Rcpp.dll in the windows package). The safe assumption is that this taints my code with the GPL, but is this really the right conclusion?

Part of my uncertainty is the tightness of the link between my code and Rcpp.dll. There are references to Rcpp in the dll, but I'm not proficient enough to know if these are references to the development environment or to calls being placed to symbols within the Rcpp library. If the former, then I believe that the Rcpp library is being linked by R and not by my library. I suspect the latter, though, since Rcpp provides a glue (sugar, actually) to simplify code-writing and execution.

There are countless related discussions related to the GPL in code distribution. To name a few:

Inside a virtual machine

Exposure of intellectual property

Consequences of GPL dependencies

Using a GPL library in commercial software

NB: I'm generally a big supporter of OSS and have participated in development and distribution in the past. Questions of "protecting code" often raise hackles of open-source programmers, frequently resulting in heated debates over software philosophy. I recognize value on both sides and want to ensure that I'm meeting the letter and (if possible) spirit of the laws. I'm not fishing for a loop-hole in the license; I'm looking for help interpreting and placing it into context.

Are R packages that depend on Rcpp required to use the GPL?

答:
Yes, if you link your code with the Rcpp library and distribute the derivative work, your package will almost certainly be subject to the GPL.  The answers to this related question apply to your situation.

Sometimes, the author of a work will offer a choice between commercial and open-source licenses (with a fee often required for the commercial option), but it doesn't appear that this is the case with Rcpp.


问:
How should be the approach to start thinking about multi thread programming
I am an experienced java developer.Of now I have started learning multithreading in java.I am able to grasp most of the concepts but still I am unable to visualize applications running on threads.I know the concept but somewhere if I am given a problem statement, I am unable to think or visualize it in threads.How should my approach be in order to start visualizing applications in threading and start coding the applications in threads?</p>

答:
The easiest way is to think of threads as processes (and this is the case in some unixy systems that spawn a new process where some systems would create a new thread).

A process is a blob of code and data with a stack and a single thread anyway.

Once there, you can start to imagine sharing data between threads- its easier in a single process with multiple threads, but dangerous. Thinking of each thread as a "process" will help visualise the importance of understanding where shared data is managed.


问:
How do I add link-time optimization capabilities to my LLVM-based compiler?
I am designing and implementing a programming language, and I am using LLVM for native code generation. Among others, performance is a key feature of the language, and as such, I am looking to implementing link-time optimization. On the official LLVM site, I've read that

LLVM features powerful intermodular optimizations which can be used at link time.

However, the page in question does not mention how a user can request link-time optimization. In particular, it only explains the theory (and some big-picture decisions of implementation) of LTO, but it does not reference any API documentation nor a tutorial.

I have performed a quick search on Clang's code base, but the results aren't too informative or relevant either – I haven't even found what settings the -flto switch turns on in Clang, let alone the changes in code generation that make it possible for the linker to optimize across object files.

Now, I suppose doing LTO should go along the lines of:

Generating some sort of metadata in the object/bitcode file so that the linker knows it can employ LTO. Maybe this needs to contain concrete information about the module, the functions to be optimized, etc. (I really have no idea what exactly should go in there...)

Then adjusting my code generation procedure (i. e. the way I am using the LLVM API) in a manner that it "supports" LTO. After some researching on the internet, I've found this related LLVM source file, so I assume it's possible to automatize at least part of this task, but – as always – the autogen'd LLVM documentation is scarce at best.

So, my question is: is my description of the process of incorporating the LTO features of LLVM in my compiler correct, and if so, can you suggest me any sort of documentation or tutorial which I could base my project on?

答:
You don't need to do anything besides generating a raw LLVM IR. Linker will take care of merging your IR modules together and compiling the resulting module - of course as long as you have your LLVM LTO plugin properly installed. LTO plugin is dumb, it will simply merge all the LLVM IR modules together.

Alternatively, you can merge your generated IR modules manually, using llvm-link tool.


答:
I usually think about thread as an arrow that execute your code(Like when you're debugging on Eclipse or Netbeans);

This little arrow executes your code, but instead of having just one, you'll spawn another one.

In Java, you have to let a class implements the Runnable interface that lets you implement the run() method;

When you want to spawn a new thread that runs in parallel than the first one you have to open an object Thread, passing the object that implements Runnable and start it.

```<code>public class SaimLol implements Runnable {
    @Override
    public void run() {
        while(true) {
            doSomethingInSaimLol();
        }
    }
}

public class Main {
    public static void main(String... args) {
        SaimLol myObject = new SaimLol();
        Thread threadSaim = new Thread(myObject);
        threadSaim.start();

        doSomethingInMain();
    }
}
</code>```

What is the thread programming goal?

When you start the thread calling the threadSaim.start() a new "arrow" spawns and the code will be executed calling concurrently the methods doSomethingInSaimLol() and doSomethingInMain();

With threads you can do things like control two parts of your code concurrently, or more advanced things like build a semaphore to let know the first thread if all variables are setted and it can goes.

Title: How should be the approach to start thinking about multi thread programming

Body: I am an experienced java developer.Of now I have started learning multithreading in java.I am able to grasp most of the concepts but still I am unable to visualize applications running on threads.I know the concept but somewhere if I am given a problem statement, I am unable to think or visualize it in threads.How should my approach be in order to start visualizing applications in threading and start coding the applications in threads?</p>

Body:
I usually think about thread as an arrow that execute your code(Like when you're debugging on Eclipse or Netbeans);

This little arrow executes your code, but instead of having just one, you'll spawn another one.

In Java, you have to let a class implements the Runnable interface that lets you implement the run() method;

When you want to spawn a new thread that runs in parallel than the first one you have to open an object Thread, passing the object that implements Runnable and start it.

public class SaimLol implements Runnable {
    @Override
    public void run() {
        while(true) {
            doSomethingInSaimLol();
        }
    }
}

public class Main {
    public static void main(String... args) {
        SaimLol myObject = new SaimLol();
        Thread threadSaim = new Thread(myObject);
        threadSaim.start();

        doSomethingInMain();
    }
}

What is the thread programming goal?

When you start the thread calling the threadSaim.start() a new "arrow" spawns and the code will be executed calling concurrently the methods doSomethingInSaimLol() and doSomethingInMain();

With threads you can do things like control two parts of your code concurrently, or more advanced things like build a semaphore to let know the first thread if all variables are setted and it can goes.


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答: If you want to make an impression on your boss, be honest.  At your weekly 1-1, ask him what is most important for you to focus on, and do that.  Try to understand what he thinks your role is, and do your best to fulfill it.  It is possible that he needs you to do certain tasks so he can concentrate on the stuff he is doing.  If you try hard to do the things he is doing, you might not be doing enough of your own task.  Find your spot on the team, excel at that, and then expand.   Tell him that you want to help out.  </p>


问:
C++ Data Server and J2ME client communication
I am working on a robot that has some AI built in. However, the mandated robot controller does not have the power to do the work onboard. This means that I need to use a co-processor.

I am writing all of my AI in C++. This will also be a TCP server. I have an idea for the protocol. The C++ server receives commands and only sends back values when absolutely required. The String for a basic command would be:

```<code>REQUEST DATA PUT data storename ENDREQ
</code>```

The C++ server would parse the request and store data under the reference of storename.

To read data from the server:

The Java request would be:

```<code>REQUEST DATA GET storename ENDREQ
</code>```

The server will reply with:

```<code>data
</code>```

I will be using TCP for the transmission of data because it seems much more robust and easy to implement using the libraries that I am using.

I am not too knowledgeable when it comes to Java, especially with J2ME. How to implement the Java side?

CHANGE:
It is quite easy for me to implement a web server on the C++ side, so please feel free to use HTTP for the protocol!

答:
Use an embedded http server - mongoose or civetweb or any of the others, they are trivially easy to implement (add a file to your build, set some options in an array, call a method to start it listening).

Then you can make http requests using java, see the 'SO tutorial'