Yan's profilecomputing lifePhotosBlogListsMore ![]() | Help |
[Alive] I miss you围着NY织的围巾,抱着NY送的大杯子,在宿舍一边哆嗦一边敲PS,不能不想。哎,欠人家好多,不知道怎么补偿…sigh~ P.S. 天灯歌词写得好挫,搞得跟一夜情样的。 [Others?]没感觉LaTeX怎么好用啊下了一个CTeX套装,把那个不太短的LaTeX教程除了数学公式以外的部分看了一遍,代码动手试了一下。没感觉LaTeX怎么好用啊。如果不看数学公式排版的话,感觉就是一个Word的功能缩减版,只不过默认样式好看一点而已。 [About] About how to read an academic bookIf we get an academic book, how should we read it? This topic is quite related to what we expect to get from the book. To seek for some information? To get an overview of a certain field? Or want to know every detail in this subject? For this article, we set the aim as to get to know the main content of the book in as little time as possible. When things come to efficiency, top-down style is useful. First we should get to know the framework of the book, i.e., what it wants to tell us and how the materials are organized. After analyzing such information, we can make decisions about what details are necessary to explore. More specifically, personally I think the procedures to read an academic book is as follows: 1. Read preface. Get to know why the author writes this book and what he wants to express. These procedures are different from traditional linear reading methods in that a lot of time is spent on deciding what to read rather than actual reading. In practicing this method in real life, this is expected to obey exactly. BTW, as some analysis is done in the reading process, a record needs to maintain for long-term reading. [Life] See ya, MSRA!Three months’ internship gets to the end finally. When looking back to this period, the first impression is it is really a hard time. Sleeping after 2:00 and getting up at 8:30 every weekday, I am usually the last one to leave while first one to come in the cubic. But certainly, I am not the most hard-working one there, while Bin and Huansen usually leaves Sigma after 3am and Lu often comes at 7am. My roommate Anh, came to apartment each 3am at first, then 5am, then sleep once every two days. “Work hard, play harder”. I don’t know whether they play harder after work, but they work really really hard. However, due to the love of this enterprise, it is really enjoyable and with sense of achievement. :-) And to my delight, among the ones staying after 2am in Sigma, most of them are from USTC. Now after touching students from various universities, I dare to say proudly that we USTCers are actually very diligent and have solid attitude and knowledge system. People in MSRA are really smart due to their hard working. Smart is not clever or agile, it can only be accumulated by long-term observations and analyzing. No matter staffs or interns, they all gave me indelible impressions that they really know much about their fields. For staffs, they can get to understand the speaker quickly even though he has quite unclear statements. And for interns, they can tell every detail of the paper when hosting paper reading, or tell you the essential reason why a system is designed like that. In MSRA, I got surprised and inspired by every one in every minute. That’s really a wonderful experience. Working with such capable people is so fascinating. And in MSRA, it is my first time to understand what friendship means. Making friends with these talented people, it is not a thing about benefits, but getting regarded and accepted. When Anh called me from U.S. when I am about to leave, hearing his voice, I really got moved. You feel happy when accompanying them, then they are your friends. With so many advantages of MSRA, I learned a lot here. This can be reflected from what I wrote in Live Space: :-) Inspiration fragments series: (1) (2) (3) I am too eager to meet you again, MSRA! See ya! [Others?]每每被古典文化的深刻所震慑君人者诚能见可欲,则思知足以自戒;将有作,则思知止以安人;念高危,则思谦冲而自牧;惧满溢,则思江海下百川;乐盘游,则思三驱以为度;忧懈怠,则思慎始而敬终;虑壅蔽,则思虚心以纳下;惧谗邪,则思正身以黜恶;恩所加,则思无因喜以谬赏;罚所及,则思无以怒而滥刑; 高中语文课本真要随身带好好读读。 [Life]Inspirations fragmentsReserve at least 1 day to revise an article. 20090926@sigma Finish work easy to concentrate first and put others into a temp drawer for future process. Improve working efficiency by being more attentive. 20090924@sigma We should always investigate before actually start an enterprise, no matter research or development. For avoiding meaningless labor, for initial motivation, and for clarifying direction. 20090916@compass People in this information age get addicted to information more or less. On the one hand, it is for lack of awareness of information filtering, which makes it very hard to delete feeds from Google Reader for example, on the other hand, it is for lack of information management ability, which drives users repeat the simple process to browse information, rather than understand, classify and manage it. 20090827@Sigma Treasure every opportunity to debug. They do cost time. 20090825@Sigma Taking photos in travelling is mainly for preserving the memory. So we should always be conscious to record memory, especially for scenes moved you and original discoveries. Taking more photos is better than missing the memory. In addition, instant sharing is also with a lot of fun. 20090823@CRH [Life][Lecture notes]Research as careerBy Baining Guo and Bin Yu Be careful when publishing papers, since you cannot draw your paper back after publication. So do quality control carefully before final submission. The really good papers will state their approaches' advantages as well as disadvantages, such as in which situations it will work good or bad and corresponding reasons. The really good papers are delivered for the development of science, rather than promoting a thought, or publishing a paper. Large amount of papers with a lot of contents overlapped will not give others a good impression, although they can indicate you did enough following work and developed the initial idea well. Follow your heart, do research for science development, for solving practical problems, rather than winning an award or publishing a paper. Be far-sighted and exceed yourself. Think about thinking, learn how to lean. Be critical to yourself and challenge yourself all the time. Only by this can you be improving. [Computing] C++ => C# => F#, more functional, more parallel (3)In this article, we will see how the functional programming style makes code parallelization extremely easy. First the parallel version of QuickSort, which is quite complex to implement in C++ but very easy in C#, is introduced. Then we will see how to make use of variables’ immutable property of function languages to parallelize code. In the end, let’s visit some useful features in .NET Parallel Extension (.NET PE), although they are less related to functional programming. Every statement is a variableRemember that in the famous C++ parallel library OpenMP, we have the “parallel for” primitive director. Using “#pragma omp parallel for”, we can simply turn a sequential for loop into a parallel one. Extending primitives in a mature language rather than defining a new one is quite reasonable and practical. That reduces the learning cost and makes the existed code still available in the extended language. However, this technique is not always effective, especially in imperative languages. For example, assume we want to implement the parallel version of QuickSort based on existed sequential source code. In C++ and OpenMP style, we may encapsulate the sequential version QuickSort(int *array, int low, int high) and Partition(int *array, int low, int high) into a new parallelized version like that: void ParallelQuickSort(int *pnArray, int nLow, int nHigh) { if (nLow >= nHigh) return; int nPivotIndex = Partition(pnArray, nLow, nHigh); int nNewLow[2], nNewHigh[2]; nNewLow[0] = nLow; nNewLow[1] = nPivotIndex + 1; nNewHigh[0] = nPivotIndex - 1; nNewHigh[1] = nHigh; #pragma omp parallel for nowait for (i = 0; i < 2; i++) QuickSort(pnArray, nNewLow[i], nNewHigh[i]); } This seems solve the problem. Yes, the function is parallel and may get a relative good result in a dual-core machine. But what if the machine has a 4-way CPU? The code still runs in 2 threads, which cannot take advantage of CPU’s potential. Of course we can manually modify the code to make it suitable for a 4-core CPU, but what if the CPU is 8-way or many-core in the future? This reveals the solution’s lack of scalability, which is critical in parallel world. An improved solution is to replace the OpenMP primitive with explicit thread creation statements. Yes, this solves previous problem, as there are more threads, with each thread occupying a core, the potential of multi-core CPUs can be used. But each thread requires a named function to specify its actions, which makes the simple QuickSort algorithm needs 4 to 5 functions to describe. In addition, remember that thread creation and switching are both very expensive. There may be more than 1000 threads running simultaneously when sorting 1 million numbers in a dual-core CPU, where the CPU is busy with switching among them rather than doing the actual work. So finally, this solution will have a bad performance in most occasions and is not practical. If we use a threading pool instead of raw threads to help distribute computation, the frequent threads switching can be avoided. A core will “pull” another thread from threading pool to process until it is free, as Figure 1 shows. Figure 1. Threading pool To this end, the problem finally gets solved in C++’s style. Quite complicated and needs a lot of background knowledge such as threading pool. Worst of all, the OpenMP library seems not providing an explicit threading pool which developers can invoke without directors like “#pragma omp parallel for”. So it is still a hard work to write practical codes. Now let’s take a look at how to implement parallel QuickSort with C# + .NET Parallel Extension (.NET PE): static void QuickSort(int[] items, int low, int high) Very similar to the sequential version. The only difference is the original QuickSort(…) turns into parallel command Task.Create(x => QuickSort(…)), which means this task is managed by threading pool and runs in parallel automatically. No extended #pragma directors, no blunt and unnecessary for loops, and certainly no need to define a totally new language, all the benefits come from the description ability of this language, in which every statement can be treated as a function variable. Just because of this feature, we can easily specify this statement should run in parallel, that one not. We can also implement functions taking functions as parameters, which helps much to build a parallel library with influent communication with users. Vivid present ability, that’s what functional programming brings to us, and builds the fundaments of an easy-to-use parallel library. We can also run this code snippet on an actual multi-core computer. In a Xeon 8-way server, sorting 10,000,000 numbers between 0 and 32767 costs 1187ms by sequential version, while only 170ms by parallel version. The acceleration ratio is about 7.0 rather than 8.0 because: First, QuickSort is a O(nlgn) level algorithm, so the theoretical acceleration ratio is about 9.3 rather than an linear result 8.0 for 10,000,000 numbers. Second, there are always overhead in parallel management, so it rarely reaches theoretical value. Third, this simple parallelization scheme does not use all the computation power, for example, all the other 7 cores has to wait and can do nothing until one core finishes partitioning all the 10,000,000 numbers. This also prevents the performance getting perfect. In conclusion, functional programming style helps to make parallelization existed code very simple and efficient. And the parallel code really works, helping us take full use of computation potential of multi-core CPUs. Immutable!As mentioned in the first article of this series, variables in functional languages are immutable, i.e. they cannot be changed after created. This helps much to parallelize existed code by avoiding writing conflicts and dead lock. In languages having functional elements like C#, such feature is also taken advantage of: string class and LINQ are typical paradigms. For objects with this property, we can write parallel version extremely easy. For example, suppose we want to select all the customers living in UK. The sequential version has been demonstrated before: var UKCustomer = from customer in customers where customer.LivingIn == "UK" select customer; To make it work in parallel, the only thing we need to do is change customers into customers.AsParallel(): var UKCustomer = from customer in customers.AsParallel() where customer.LivingIn == "UK" select customer; The .NET Parallel Extension will do all the implementation and optimization work for you. Thanks to the immutability of variables in LINQ, developers as well as compilers needn’t worry about complex locks, semaphores, etc. So that there can be a simple pattern to parallelize code, which makes an easy-to-use library possible. This pattern is called PLINQ in C#, while in F# where nearly all the variables are immutable, parallelization is even simpler, often we only need to replace “let” primitive with “let!” and everything is done. .NET Parallel ExtensionBesides taking use of functional style to make parallel programming quite easy, .NET PE has other very useful data structures. Let’s take a brief look. FutureFuture is like Task class mentioned before. It creates another “thread” in threading pool and starts it in proper time. However, unlike Task instances, Future instances can return an object as result, which appears as Value property. When some thread tries to refer to the Value property of a Future object, it will get the result immediately if the Future object has finished the computation, or gets blocked until the Future’s work gets done. It provides an alternative to events and semaphores, so that the code can be more readable and error-prone. For example, we can count a tree’s nodes like this: int CountNodes(Tree<int> node) { if (node == null) return 0; var left = Future.Create(() => CountNodes(node.Left)); int right = CountNodes(node.Right); return 1 + left.Value + right; } WriteOnceMany parallel algorithms, especially those allowing concurrent writing, rely on variables that can only be changed once, such as a lot of sorting algorithms. WriteOnce class just provides an implementation of such data structure. BlockingCollectionIn the classical producer/ consumer problem, there is expected a pipeline where all the producers can put their products in and all the consumers can fetch tasks from. In addition, the consumers will get blocked when there is no task in the pipeline. This is exactly BlockCollection does in .NET PE. It provides a thread-safe implementation for concurrently reading and writing, and automatically blocking when it is empty. From the three useful components in .NET PE, we can see that this extension library is from practical programming and consider developers’ real needs, and get a lot of benefits from functional programming style. SummaryEvery statement in a functional language is a variable, so that we can describe our intention and communicate to the compiler with more powerful vocabularies. In addition, as variables in functional languages are immutable, it enables compiler to provide extremely easy way to parallelize code. From these two factors, we can see that functional programming style does help us write parallel code more easily. And that is more functional, more parallel. P.S. Note that parallel programming is quite complex, while this series of articles only cover very little part of it. To write practical parallel codes with scalability, robustness and good performance needs knowledge about parallel algorithm, hardware architecture as well as programming language and extension library. Anyway, functional style does simplify the parallel coding procedure and provide new solutions to some sequential problems, although it has fewer effects on algorithms. [Alive]周末柳浪庄,愿为持竿叟周末玩的很爽。杀人百发百中,当杀手或者警察几次都是两天结束战斗。除了首轮被砍死之外一般都坚持到最后,充分体现了天蝎的伪装天赋和过人直觉。涛哥的“俺是平民”无比搞笑,鹿师兄太猛了,分析得头头是道,而且当法官的时候太恶搞了…啊~~好喜欢这帮人~~ 到家了突然想起来还有个好高级的麦当劳可乐没有兑换。然后就用这个彩信跑去兑。就看服务员搞出来一个机器扫了一下,吱吱吱就吐出来一张纸,上面有我的手机号,要兑换的东西等等,然后就拿到了。超级高级。 [Computing] C++ => C# => F#, more functional, more parallel (2)In this article, I will introduce two sample scenes to demonstrate how we can use functional programming to make the code more intuitive, more elegant and more parallel. Text editingConsider we want to implement some text editing interface on mobile platform. First, some rich text, i.e. the mixture of texts and images are shown on the screen. Then when users tap on some text, an editing panel will pop up, where users can do some editing work. When the editing finishes, users can tap on some button to return to the original interface, where the texts are modified according to the editing. As following flow chart shows.
The obstacle is how event handler B knows which label’s text should he updated. Obviously no one knows this until user taps a label, when the information which label is tapped is delivered to event handler A by OS. Then how to communicate between A and B seems trivial. A member variable will do a good job in C++. Considering in C++ we cannot create functions at runtime, the final architecture will be like this: First, event handlers A and B appear as existed functions in a class, with a member variable L. When A is invoked, he first assigns L as the tapped label, then shows the editing panel. And when B is invoked, i.e. the finish editing button is clicked, he reads text from editing panel, and assign L’s text. Not too complex huh? Let’s see another way in C#, a language with many functional elements. As B needs information undecided until A is invoked, then why not create an event handler in A to do B’s work, dynamically? From this motivation, we have codes below, with no member variables to communicate between A and B: //this is event handler A, where the parameter sender indicates which label is tapped. void Label_Click(object sender, EventArgs e) { //add an editing panel. //... ... //create event handler B finishingButton.Click += (object textBoxSender, EventArgs ea) => { (sender as Control).Text = (textBox as TextBox).Text; //assign text after editing to the sender //please note that sender is not a local variable in event handler B, //but a parameter from event handler A. this.Controls.Remove(outerPanel); outerPanel.Dispose(); //delete editing panel and release resources. }; //some other codes ... ... } Please note that sender in B is from A, i.e. for every label clicked, A will create a different event handler and bind it to click event of finishing button. Isn’t it amazing? Although I cannot see any direct advantages from this change, but it appears more fun, more flexible and more readable. :-) WebPages downloadingIt seems very fundamental to download a web page from the internet. But it is a time consuming task so that often involves multi-threading to improve efficiency. Let’s see the typical solutions to download 10 WebPages in C++ and C#. In C++, to download a webpage, we should first create a new thread explicitly, assign it a webpage, and then start the thread. Fortunately, there are no interactions among the threads, so this simple scheme works. Let’s see how we can deal with this task in C# with asynchronous functions: HttpWebRequest req = HttpWebRequest.Create(http://g.cn); req.BeginGetResponse((IAsyncResult ar) => { HttpWebResponse rsp = req.EndGetResponse(ar); Stream stream = rsp.GetResponseStream(); //Redirect the stream to a file … … }); We can see that HttpWebRequest class has a method named BeginGetResponse, which takes a function as parameter. This method will create a thread to do the work, and when the work finishes, the function as parameter will be invoked, in which we can deal with the result. This code in C# does the same thing as previous C++ one, in spite of the built-in load balance feature of C# threads. But it shows a new way to write codes if functions can be created, destroyed, passed as parameter dynamically at runtime, just as other kinds of variables do. Of course these two samples do not demonstrate most fundamental differences between imperative programming and functional programming. But they do demonstrate some differences in how we treat functions; at least provide some fun solutions. It makes no sense to judge which one is better, but having more candidate solutions is not a bad thing, right? (To be continued… We haven’t seen how to write parallel code with functional languages yet. And I personally insist that functional programming style in these two samples shows much more flexibility and potential than traditional imperative ways. When finding more persuasive examples, I will show you! ;-) [Life] Get on with human beingsWe are meeting human beings every day, and have to cooperate with them to achieve great goals. However, for Chinese student especially the only child in the family, how to get on with classmates, colleagues, and leaders is an issue being overlooked for a long time. I have to admit that I even don’t how to make friends before my entering MSRA. Ice breakingMaybe the most important thing in ice breaking is the awareness of making friends with others. Of course, it is very easy and comfortable to stay alone, avoid others’ eye contact, and say no to any changes. But as Iris told me: look, you entered MSRA and got to know some colleagues. Then what about three months later if you are not active enough? You still don’t know much about them or contact them often. The most important resource in Microsoft, so many brilliant and promising people, gets wasted, because of your laziness, recreance and fear to changes. The statements shocked me and inspired me to think about an issue never thought before, friends. Making friends seems the most common and easiest thing to do, considering everyone has friends, and even some close ones. However, as it is so common, the significance and difficulty is often ignored. Simply sitting there will not bring you a lot of friends, although it is often most comfortable. We have to stand up and pursue friends, the most common and valuable resource around us, although this process may also bring embarrass, enmity or frustration. So the first step of ice breaking, i.e. breaking the icy wall between you and your future friend, is smile. Just deliver friendly signals to a stranger you are interested in. But unfortunately, this is sometimes ineffective in China, especially for young people adapted to their families’ care and having intuitive guards against strangers. So please be patient, send friendly signals continuously, and you two will get familiar soon. Be friendly and patient, I think these are the most important tips in ice breaking. Of course, it will be better if you can create opportunities to meet often. Getting alongIn fact I still don’t know the meaning of friends and what we should expect friends to bring us. But there are at least some skills to avoid conflicts and enmity among people. Observation, I think this is the fundamental of getting along with anyone. Observe his/ her reaction to some certain events, and this can bring a lot. My personal habit is to infer and analyze others’ inside psychological activities when observing. The inference and following verification process can tell me his characteristics, attitudes, sensitiveness and most importantly, what he will react to another event. Such information helps a lot to select talking topics and avoid offensive words. Making the inference and records explicit like computers do, seems weird but really effective. :-) Getting along with other people is certainly not simply talking and having dinner together totally based on intuitions. We can achieve little without explicit efforts. Oh, let me stress it again, these are all my personal opinions, and everyone has his/ her own understanding to friends and human beings. Be romanticWhen you pay attention to friends, don’t forget ones you love, mom, dad, lover… Besides avoid offending them, why not create some surprise to show your sincere care and love? In China, this is especially a problem, because most youth are used to parents’ love while others never think about expressing their love. Thanks to Ngo Hai Ha, or I’ll also never consider this affair. She taught me that love should be shouted out as well as hidden in every detail of life. And I admit Vietnamese are the most romantic people in the world. :-) Don’t be so shy, just buy a bouquet of flowers and give it to your parents, hold a birthday party for them, and take them out to have a good dinner. And watching the excited faces you beloved, you will also be moved. Why not yell your love out? Just try try try… TechnologySeems not so proper to put this part on… but I really wrote a program to reply text messages from my girlfriend automatically… saves a lot of time and now she is much more satisfied by my quick responses. XD [Others?]Recommend: Windows Live software seriesDuring these days’ internship in MSRA, I began to use Windows Live software series such as Movie Maker and Photo Gallery, and to my surprise, they are quite useful, before which I thought Windows Live software suite is very light-weighted and only for freshmen. I used Adobe Premiere for video editing at school (according to copyright law in China, students can use business software without charge for non-business purposes). However, it is too large, too complex and always costs a lot of time to render the result video, sometime even crashes. It is the first time when I met Windows Live Movie Maker in MSRA, making up a demo video. It is so easy to use! Suddenly I understood why Anh always told me this food is easy to eat, that’s not. There are differences in software too. Just clicking, dragging, and… done! In fact, I just want to put some video clips together, add some transition animations and subtitles. Of course Premiere can do that, but Movie Maker is much simpler and stable, most important, it is suitable for such kinds of task. Get things done easily and quickly, why not? Photo Gallery stepped in my life after our travelling to Qingdao. In Qingdao, I captured a lot of photos in one place with continuous while different angles, and wanted to make a panorama in the computer. However, it is really hard to find software that works. I tried open-source software hugin, business software ptgui, and some research products, but they all mentioned a lot of complex parameters, worked slowly and worst of all, they all crashed in my personal computer and reported unfriendly information: unhandled exception at 0xxxxxx, cannot find xxx.dll, xxx parameter in SIFT incorrect. Fortunately, I met Windows Live Photo Gallery (so long a name…), just selecting photos and click “Make panorama”, then everything is done. No complicated parameter setting, no annoying multi-step wizard, one click and get a result. That’s exactly what I want. Thanks to these small tools, I can deal with my life easily. Generate panoramic images with Photo Gallery, make a video clip to narrate related story with Movie Maker, and write a blog post to show off with Writer. Suitable, this is why I recommend Windows Live software series. P.S. for more professional photo handling tools such as advanced stitching or collage making, please visit http://blogs.msdn.com/pix/pages/extras.aspx. [Others?]Some tips about Windows Live SpaceWhen beginning to blog my life 3 years ago, I tried various BSPs, sina, QQ, etc. Finally I determined to use Windows Live Space because only here I could change the background into pure black…囧 However, as time went on, Live Space appears more and more inconvenient: cannot insert gif images, lack of formatting flexibility, code always so ugly here… until today, when I try to search the internet for how to make full use of my Live Space. Fortunately I found this article (in Chinese, so as following links). It is an index about tips of Windows Live Space. In this one, you will learn how to add borders to a paragraph with a different style. And in this one, method to add dynamic video contents is introduced. And of course, more resources are here. Just explore by yourself. :-) [Computing] C++ => C# => F#, more functional, more parallel (1)On DotNet Board of USTC BBS, orochi recommended a book named “Functional Programming For The Real World”. It demonstrates advantages of functional programming towards traditional imperative programming, which inspires me a lot. Here, I will first narrate my understanding of such advantages as a C# developer, then take an example to address how the programming pattern changes from pure imperative language as C++, to C# which contains a lot of functional programming elements, then to typical functional language F#. As I mentioned in this blog before, functional programming is another programming paradigm besides imperative programming. It is based on lambda calculus, which is as descriptive as a Turing machine. Anyway, this statement demonstrates nothing valuable. Let see the differences between imperative programming and functional programming in detail: 1. Function is treated as the fundamental element in functional programming. In functional programming languages, functions can be treated as independent variables (instead of considered as a pointer in languages like C++), can be created and destroyed dynamically like other kinds of variables, and can have no name (i.e. anonymous). This is a difference, but I admit that I haven’t found any advantages caused by this point directly. L Maybe when finish the studying of F#, I can answer this question. :-) 2. Functional programs tell computer what to do rather than how to do it. For example, if we want to select all the costumers living in UK, we may write like this in imperative languages like C++: for(vector<CCustomer>::const_iterator i = Customers.begin(); i != Customers.end(); ++i) This code snippet tells the computer: first pick up a customer from the customer list, check whether he/she lives in UK, if so, copy it to a new list called UKCustomers, do noting otherwise, then pick up next and do the same thing, until all the customers are processed. We are quite familiar with such “algorithms”, huh? Let’s see how we tell the computer to do the same thing with C#: var UKCustomer = What we need to do is just tell the computer: to pick up all the customers living in UK. Tell the computer what to do rather than how to do, this is called declarative style, which is used by popular languages such as SQL, as well as functional programming languages. 3. Variables in functional languages are immutable, i.e. they cannot be changed after created and initialized. A little advantage caused by this feature is, the codes is easier to understand and with less ambiguous. For example, without reading the manual, we don’t know what is the result of rectangle.Inflate(int width, int height). Will it inflate the original rectangle or return a new inflated rectangle? Both the choices are reasonable. However, in the functional world, only the second situation is possible. Of course, this style is not intended to save the “mass world” of imperative languages, but to make it possible that: 4. Write parallel code very easily. As every object in functional language is immutable, there will be no blocking, no lock or no writing collisions in the multi-thread world. Furthermore, it becomes very cheap to recognize which part of the program can be executed currently, so that the automatic optimization by the compiler is possible. That means, we need only make some tiny changes, then the program can run on multi-core computer or clusters with compiler’s optimizations. Take the sample code mentioned in the o_Ops! T-Shirt: girls.Where(x => x.IsBeauty).All(x => { x.Hi(); return true; }); which means say hi to all the beautiful girls in a list named girls. If you are a mono-core computer, you have to select all the beautiful girls, then say hi to them one by one. It is very uncompetitive, isn’t it? So we can modify the program like this, with the help of Parallel Extensions of .NET, which you can download here: girls.AsParallel().Where(x => x.IsBeauty).All(x => { x.Hi(); return true; }); Now you can say hi to all the beautiful girls simultaneously, with enough cores. :-) is it simple? No explicit processes or threads, no configuration for MPI or OpenMP. Thanks to the immutability of LINQ in C# 3.0, parallel programming turns so simple. (to be continued… next part you will see how we accomplish part of a map rendering engine in C++, C# and F#, demonstrating how the functional programming paradigm makes parallel coding so easy and natural.) [Alive]寂寞周日晚上,从紫金走向Sigma的感觉和从宿舍楼走向三教的感觉是一样的。 P.S. 在facebook上做了一个心理测试,挺好玩的: |
|
|