Monthly Archives: May 2013
“The Best Programming Advice I Ever Got” with Andrei Alexandrescu | | InformIT
“The Best Programming Advice I Ever Got” with Andrei Alexandrescu | | InformIT.
learning how to learn is more important than learning anything else….
Creating a Thread using C++ Boost Lib.
Creating a thread is deceptively simple. All you have to do is create a thread object on the stack or the heap, and pass it a functor that tells it where it can begin working. For this discussion, a “thread” is actually two things. First, it’s an object of the class thread, which is a C++ object in the conventional sense. When I am referring to this object, I will say “thread object.” Then there is the thread of execution, which is an operating system thread that is represented by the thread object. When I say “thread” , I mean the operating system thread. Let’s get right to the code in the example. The thread constructor takes a functor (or function pointer) that takes no arguments and returns void. Look at this line from below code,
boost::thread myThread(threadFun);
This creates the myThread object on the stack, which represents a new operating system thread that begins executing threadFun. At that point, the code in threadFun and the code in main are, at least in theory, running in parallel. They may not exactly be running in parallel, of course, because your machine may have only one processor, in which case this is impossible (recent processor architectures have made this not quite true, but I’ll ignore dual-core or above processors and the like for now). If you have only one processor, then the operating system will give each thread you create a slice of time in the run state before it is suspended. Because these slices of time can be of varying sizes, you can never be guaranteed which thread will reach a particular point first.
This is the aspect of multithreaded programming that makes it difficult: multithreaded program state is nondeterministic. The same multithreaded program, run multiple times, with the same inputs, can produce different output. Coordinating resources used by multiple threads is the subject of my next post.
After creating myThread, the main thread continues, at least for a moment, until it reaches the next line:
boost::thread::yield( );
This puts the current thread (in this case the main thread) in a sleep state, which means the operating system will switch to another thread or another process using some operating-system-specific policy. yield is a way of telling the operating system that the current thread wants to give up the rest of its slice of time. Meanwhile, the newthread is executing threadFun. When threadFun is done, the child thread goes away. Note that the thread object doesn’t go away, because it’s still a C++ object that’s in scope. This is an important distinction.
The thread object is something that exists on the heap or the stack, and works just like any other C++ object. When the calling code exits scope, any stack thread objects are destroyed and, alternatively, when the caller calls delete on a thread*, the corresponding heap thread object disappears. But thread objects are just proxies for the actual operating system threads, and when they are destroyed the operating system threads aren’t guaranteed to go away. They merely become detached, meaning that they cannot later be rejoined. This is not a bad thing. Threads use resources, and in any (well-designed) multithreaded application, access to such resources (objects, sockets, files, rawmemory, and so on) is controlled with mutexes, which are objects used for serializing access to something among multiple threads.
If an operating system thread is killed, it will not release its locks or deallocate its resources, similarly to how killing a process does not give it a chance to flush its buffers or release operating system resources properly. Simply ending a thread when you think it ought to be finished is like pulling a ladder out from under a painter when his time is up.
Thus, we have the join member function. As in below code, you can call join to wait for a child thread to finish. join is a polite way of telling the thread that you are going to wait until it’s done working:
myThread.join( );
The thread that calls join goes into a wait state until the thread represented by myThread is finished. If it never finishes, join never returns. join is the best way to wait for a child thread to finish. You may notice that if you put something meaningful in threadFun, but comment out the use of join, the thread doesn’t finish its work. Try this out by putting a loop or some long operation in threadFun. This is because when the operating system destroys a process, all of its child threads go with it, whether they’re done or not. Without the call to join, main doesn’t wait for its child thread: it exits, and the operating system thread is destroyed.
If you need to create several threads, consider grouping them with a thread_group object. A thread_group object can manage threads in a couple of ways. First, you can call add_thread with a pointer to a thread object, and that object will be added to the group. Here’s a sample:
boost::thread_group grp;
boost::thread* p = new boost::thread(threadFun);
grp.add_thread(p);
// do something…
grp.remove_thread(p)
When grp’s destructor is called, it will delete each of the thread pointers that were added with add_thread. For this reason, you can only add pointers to heap thread objects to a thread_group. Remove a thread by calling remove_thread and passing in the thread object’s address (remove_thread finds the corresponding thread object in the group by comparing the pointer values, not by comparing the objects they point to). remove_thread will remove the pointer to that thread from the group, but you are still responsible for delete-ing it. You can also add a thread to a group without having to create it yourself by calling create_thread, which (like a thread object) takes a functor as an argument and begins executing it in a new operating system thread. For example, to spawn two threads in a group, do this:
boost::thread_group grp;
grp.create_thread(threadFun);
grp.create_thread(threadFun); // Now there are two threads in grp
grp.join_all( ); // Wait for all threads to finish
Whether you add threads to the group with create_thread or add_thread, you can call join_all to wait for all of the threads in the group to complete. Calling join_all is the same as calling join on each of the threads in the group: when all of the threads in the group have completed their work join_all returns.
Creating a thread object allows a separate thread of execution to begin. Doing it with the Boost Threads library is deceptively easy, though, so design carefully.
#include <iostream> #include <boost/thread/thread.hpp> #include <boost/thread/xtime.hpp> struct MyThreadFunc { void operator( )( ) { // Do something long-running... } } threadFun; int main( ) { boost::thread myThread(threadFun); // Create a thread that starts // running threadFun boost::thread::yield( ); // Give up the main thread's timeslice // so the child thread can get some work // done. // Go do some other work... myThread.join( ); // The current (i.e., main) thread will wait // for myThread to finish before it returns }
Related articles
- SINGLETON in Multithreaded Environment (aishwaryavaishno.wordpress.com)
- Synchronising Multithreaded Integration Tests revisited (java.dzone.com)
- Working With Threads (androidstudies.wordpress.com)
- Adventures in Parallel Universe Part 1 (lastsector.wordpress.com)
Project Euler Problem#13 solution in C++
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690
Solution:
#include <stdio.h> #include <iostream> #include "projectEulerProblem13.h" //data is stored in char data[100][51] in this file. int main () { int x, y, columnSum[50], carry = 0; for (x = 49; x >= 0; x--) { columnSum[x] = carry; for (y = 0; y < 100; y++) { columnSum[x] += (int)data[y][x] - 48; } carry = columnSum[x] / 10; } std::cout << carry << std::endl; for (x = 0; x < 50; x++) { std::cout << (columnSum[x] % 10) << std::endl; } return 0; }
Related articles
- Project Euler Problem#10 solution in C++ (alikhuram.wordpress.com)
- Project Euler Problem#12 solution in C++ (alikhuram.wordpress.com)
- Project Euler Problem#11 solution in C++ (alikhuram.wordpress.com)
Some advice for college freshmen
I don’t know the author but this seems a very good advise for fresh Graduates.
Strong skill of one or more good languages like C++, Java and C#:
Must have strong skills with control structures. Don’t mess up if you’re asked to print out triangle or other shaped piles of ‘x’s with loops.
Must have strong skills with recursion. You must know how to transform a looped task into a recursive one and vice versa, for example: multiplication using addition recursively.
If your language is C/C++, you must know how to play with pointers and references.
Understand pass by value and reference.
Clearly understand scopes and memory allocation, de-allocation. Know when an object is destroyed and when to destroy.
Know the usage of all operators including bit-wise ones.
In-depth knowledge of OOP:
Only being able to write classes and doing encapsulation and inheritance is not what you should call good OOP.
Clearly understand how function overloading, overriding, polymorphism works.
Clearly understand how constructor/destructor (if any) works with inheritance.
Clearly know the difference and use of Interfaces and Abstract classes.
Know how to overload operators. Why and how copy constructor is defined/used.
Know common data structures:
At least know the common data structures like stack, queue, linked list, doubly linked list (know circular version of all of them) and trees.
Be a skilled implementer of any of those, have clear concept of how push, pop, add, delete, peek etc method works on those data structures.
Know most common algorithms well:
You don’t need to memorize pseudo codes line by line but you need to have clear concept of most common algorithms of sorting(bubble, quick, merge, heap, bucket, etc), searching (including DFS, BFS), etc.
As a fresher you must know their time and space complexities, pitfalls and improvements (if any).
General computing concepts:
Know processes and threads, how are they related to each other, how to program them, etc.
Understand TCP/IP: Don’t think it’s only the network administrator’s task to understand TCP/IP. All programmers ever doing any network or web programming should have clear TCP/IP concepts and understanding.
Be skilled in debugging in IDEs:
Be skilled in any of Visual Studio/Visual Studio.Net, Eclipse, Netbeans, KDevelop, etc.
Know how to debug your code.
Have basic knowledge of Software Engineering and SDLC.
General Advise:
Start with C++ or Java, avoid starting with scripting languages:
If you’re learning programming for the first time, avoid starting with scripting or loosely typed languages like: PHP, ASP, Perl, etc or Visual Basic. It may destroy your understanding of program execution, data types, memory allocation, etc.
Start with C++ or Java. If you want to me to be specific, start with C++, you’ll love it for the rest of your life.. 🙂 It’ll be easier for you to learn (almost) any other language (like: C#, PHP, ASP, etc).
If you ask, do you need to know C to start with C++? Or should you learn C first and then C++? C definitely helps a lot for learning C++ but it’s not mandatory to start with C.
If you want to be a good programmer, keep on coding at least 20 hours a week for the next 4 years :). Never stop learning new technologies that are coming out everyday. Know some of the many languages/technologies but be master of one. Know at least one language very well.
Related articles
- 10 Reasons to Learn Java Programming Language and Why Java is Best (javarevisited.blogspot.com)
- Busting KDevelop myths (scummos.blogspot.com)
- How to represent OOP concepts in algorithms in a standard way? (cs.stackexchange.com)
- 7 Habits Of Successful College Freshmen (howtolearn.com)
Write Random Numbers to a File and Read Into Vector in C++
// Programmer: Graham Nedelka
// Output random numbers to file, read in via vector
//
#include <iostream>
#include <fstream>
#include <vector>
#include <time.h>
using namespace std;
int main () {
srand (time(NULL));
ofstream myFile(“data.dat”);
for (int i = 0; i < 1000000; i++)
myFile << rand() % 10000 + 1 << endl;
vector<int> newVector;
ifstream myRead;
myRead.open(“data.dat”);
int x;
while (!myRead.eof())
{
myRead >> x;
newVector.push_back(x);
}
myRead.close();
for (int i = 0; i < newVector.size(); i++)
cout << newVector[i] << endl;
sort(newVector.begin(), newVector.end());
for (int i = 0; i < newVector.size(); i++)
cout << newVector[i] << endl;
return 0;
}
Agile software development – get back to basics to make it work
For some years, Agile methodologies have been widely adopted within the information technology software world to bring new products and services to market quickly and efficiently, increasingly taking over from more traditional approaches such as ‘waterfall’. While it may have promised much, Agile has not been without its critics, who say that it does not live up to expectations, that users can become too bogged down in the processes and lose sight of the end goal. They also fear Agile projects become siloed into teams, rather than being visible to the organisation as a whole.
However, as an increasing number of companies are finding, Agile CAN deliver on expectations, if some simple principles are followed: what might be called “pragmatic agile”. Supporting tools also have a role, such as SCM (software configuration management). SCM can help ensure that a project remains visible to all the key stakeholders, while supporting Agile-related…
View original post 1,363 more words