Posts List

chrome源码之 Synchronization

In Chrome code, message passing is far more common (via TaskRunner and PostTask) and low-level synchronization primitives like locks, condition variables and waitable_event should be used only when necessary. This article introduce the implement of synchronization mechanism in chrome source code. Some additional motivation: Condition variables are nearly impossible to implement correctly on Windows XP or earlier. Chrome’s implementation is correct, but very slow. Whenever you use a CV you are disproportionately harming our performance on Windows. A lot of times people just want to wait on a boolean. In such cases, if message passing cannot work, please use WaitableEvent instead. Lock The Lock class implements a mutual exclusion lock, or mutex for short. A mutex is used to permit only one thread at a time to have exclusive access to some resource, which is typically some variable or data structure. Mutexes are so common that many words have been coined to describe their operation. // A convenient wrapper for ...

Permutation and Combination

Permutation and combination are traditional maths problems, both of which have to do with lists recursively. This article compares Erlang, Javascript, Python and Scheme, each of which implements both of the problems, and it can test the expressive ability to process lists of a language. Theory List permutation: [1,2,3] -> [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] To list L: Choose any one element of L as the first element Head Elements behind Head, should be chosen from a list which is excluded the Head element from L Recognize the recursive feature: every item of the permutation of the left list, should be added to Head to build a complete item result. List combination: [1,2,3] -> [1,2,3], [1,2], [1,3], [1], [2,3], [2], [3] To list L: Every element of L has two choices, use it or not Should exclude the situation of choosing null Erlang Erlang has the ability of list comprehension, so as to deal with list recursively easily. And ...

chrome源码之 Lazy Instance

Lazy instance is an object which is created on the first time it’s accessed. And chrome implements a very powerful LazyInstance template class, which is very fast and thread safe. See detail in ( lazy_instance.h ). Class: LazyInstance<Type, Traits> The LazyInstance<Type, Traits> class manages a single instance of Type, which will be lazily created on the first time it’s accessed. This class is useful for places you would normally use a function-level static, but you need to have guaranteed thread-safety. The Type constructor will only ever be called once, even if two threads are racing to create the object. Get() and Pointer() will always return the same, completely initialized instance. When the instance is constructed, it is registered with AtExitManager. The destructor will be called on program exit. LazyInstance is completely thread safe, assuming that you create it safely. The class was designed to be POD initialized, so it shouldn’t require a static constructor. It really only makes sense to ...

Linus Trovalds 谈Linux内核开发管理风格

这篇短文是描述了一种“理想的”(当然也可以说是“自以为是的”,各种看法因人而异)Linux内核开发管理风格。这篇文章从某种意义上来说就和编码规范文档差不多,有了这篇文档,就可以避免总是重复地回答同样(或者类似)的相关问题。 管理风格其实是因人而异的,而且很难像编码风格一样,单纯用数量来衡量。因此这篇文档无法保证一定具有实 ...

chrome源码之 Thread和MessageLoop

Threads are very useful in application to deal with multi-thread problems, and chrome wrapped a series of excellent classes: base::Thread, MessageLoop and so on. Thread A simple thread abstraction that establishes a MessageLoop on a new thread. The consumer uses the MessageLoop of the thread to cause code to execute on the thread. When this object is destroyed, the thread is terminated. All pending tasks queued on the thread’s message loop will run to completion before the thread is terminated. WARNING! SUBCLASSES MUST CALL Stop() IN THEIR DESTRUCTORS! See ~Thread(). After the thread is stopped, the destruction sequence is: Thread::CleanUp() MessageLoop::~MessageLoop MessageLoop::DestructionObserver::WillDestroyCurrentMessageLoop Thread class classBASE_EXPORT Thread : PlatformThread::Delegate { public: struct Options { Options() : message_loop_type(MessageLoop::TYPE_DEFAULT), stack_size(0) {} Options(MessageLoop::Type type, size_t size) : message_loop_type(type), stack_size(size) {} MessageLoop::Type message_loop_type; size_t stack_size; }; explicit Thread(const char* name); // Destroys the thread, stopping it if necessary. // // NOTE: ALL SUBCLASSES OF Thread MUST CALL Stop() IN THEIR DESTRUCTORS (or // guarantee Stop() ...

chrome源码之 Value和JsonParser

Class base::Value is a variant type to holder complex data, this article introduce the use of base::Value in chrome source code. base::Value The Value class is the base class for Values. A Value can be instantiated via the Create*Value() factory methods, or by directly creating instances of the subclasses. classBinaryValue; classDictionaryValue; classFundamentalValue; classListValue; classStringValue; classValue; classBASE_EXPORT Value { public: enum Type { TYPE_NULL = 0, TYPE_BOOLEAN, TYPE_INTEGER, TYPE_DOUBLE, TYPE_STRING, TYPE_BINARY, TYPE_DICTIONARY, TYPE_LIST }; static Value* CreateNullValue(); // other types use new FundamentalValue or new StringValue etc. Type GetType() const { return type_; } bool IsType(Type type) const { return type == type_; } virtual bool GetAsBoolean(bool* out_value) const; virtual bool GetAsInteger(int* out_value) const; virtual bool GetAsDouble(double* out_value) const; virtual bool GetAsString(std::string* out_value) const; virtual bool GetAsString(string16* out_value) const; virtual bool GetAsList(ListValue** out_value); virtual bool GetAsDictionary(DictionaryValue** out_value); // Subclasses return their own type directly in their overrides; virtual Value* DeepCopy() const; // Compares if two Value objects have equal contents. virtual ...

chrome源码之 WeakPtr

WeakPtr is normally used to avoid recursive reference, this article introduce the use of WeakPtr and WeakPtrFactory in chrome source code. Weak pointers are pointers to an object that do not affect its lifetime, and which may be invalidated (i.e. reset to NULL) by the object, or its owner, at any time, most commonly when the object is about to be deleted. Weak pointers are useful when an object needs to be accessed safely by one or more objects other than its owner, and those callers can cope with the object vanishing and e.g. tasks posted to it being silently dropped. Reference-counting such an object would complicate the ownership graph and make it harder to reason about the object’s lifetime. Weak pointers must always be dereferenced and invalidated on the same thread, otherwise checking the pointer would be racey. WeakPtrFactory enforces this by binding itself to the current thread when a WeakPtr is first created and un-binding only when those ...

哈佛图书馆墙壁训言

1、此刻打盹,你将做梦;此刻学习,你将圆梦。 This moment will nap, you will have a dream; But this moment study,you will interpret a dream. 2、我荒废的今日,正是昨日殒身之人祈求的明日。 I leave uncultivated today, was precisely yesterday perishes tomorrow which person of the body implored. 3、觉得为时已晚的时候,恰恰是最早的时候。 Thought is already is late, exactly is the earliest time. 4、勿将今日之事拖到明日。 Not matter of the today will drag tomorrow. 5、学习时的苦痛是暂时的,未学到的痛苦是终生的。 Time the study pain is temporary, has ...

chrome源码之 Move Constructor

Move constructor is a idiom in C++ for efficiency( use move if possible instead of copy ), this article introduce the implement of move constructor in chrome source code ( move.h ). Move constructor is used to transfer the ownership of a resource held by an object to another object in C++03 effectively. Note: In C++11, move-constructors are implemented using the built-in rvalue reference feature. An implemnt of move constructor in chrome: // move.h #ifndef BASEMOVE_H #define BASEMOVE_H #define MOVE_ONLY_TYPE_FOR_CPP_03(type, rvalue_type) \ private: \ struct rvalue_type { \ explicit rvalue_type(type* object) : object(object) {} \ type* object; \ }; \ type(type&); \ void operator=(type&); \ public: \ operator rvalue_type() { return rvalue_type(this); } \ type Pass() { return type(rvalue_type(this)); } \ private: #endif//BASEMOVE_H We see that the MOVE_ONLY_TYPE_FOR_CPP_03 macro has 4 parts: rvalue_type typedef: can hold the host type host defines private reference copy constructor and assign operator host can auto convert to rvalue_type Pass() method: host should implement constructor ...

chrome源码之 scoped_ptr

Smart_ptr are useful in C++ for auto-manage of memory, this article introduce scoped_ptr in chrome source code. Scopers help you manage ownership of a pointer, helping you easily manage the a pointer within a scope, and automatically destroying the pointer at the end of a scope. Auto management of ownership // scoped_ptr<T> { scoped_ptr<Foo> foo(new Foo("wee")); } // foo goes out of scope, releasing the pointer with it. { scoped_ptr<Foo> foo; // No pointer managed. foo.reset(new Foo("wee")); // Now a pointer is managed. foo.reset(new Foo("wee2")); // Foo("wee") was destroyed. foo.reset(new Foo("wee3")); // Foo("wee2") was destroyed. foo->Method(); // Foo::Method() called. foo.get()->Method(); // Foo::Method() called. // SomeFunc takes ownership, foo no longer SomeFunc(foo.release()); // manages a pointer. foo.reset(new Foo("wee4")); // foo manages a pointer again. foo.reset(); // Foo("wee4") destroyed, foo no longer // manages a pointer. } // foo wasn't managing a pointer, so nothing was destroyed. // scoped_ptr<T[]> { scoped_ptr<Foo[]> foo(new Foo[100]); foo.get()->Method(); // Foo::Method on the 0th element. foo[10].Method(); // ...

chrome源码之 Bind和Callback

Class base::Bind and base::Callback in chrome are just like bind/function in boost, which are used to bind and store functions. The template Callback class is a generalized function object. Together with the Bind() function in bind.h, they provide a type-safe method for performing partial application of functions. The Callback objects themselves should be passed by const-reference, and stored by copy. They internally store their state via a refcounted class and thus do not need to be deleted. The reason to pass via a const-reference is to avoid unnecessary AddRef/Release pairs to the internal state. Binding a bare function int Return5() { return 5; } base::Callback<int(void)> func_cb = base::Bind(&Return5); func_cb.Run(); Binding a member function The first argument to bind is the member function to call, the second is the object on which to call it. classRef : public base::RefCountedThreadSafe<Ref> { public: int Foo() { return 3; } void PrintBye() { LOG(INFO) << "bye."; } }; By default the object must support ...

chrome源码之 RefCounted和scoped_refptr

RefCount is a useful and common technique in c++, this article introduce RefCount and scoped_refptr in chrome source code ( ref_counted.h ). RefCounted A base class for reference counted classes. template <classT> classRefCounted; classMyFoo : public base::RefCounted<MyFoo> { protected: ~MyFoo() {} friend classbase::RefCounted<MyFoo>; }; Note: If MyFoo has a destructor with private or protected property, friend class base::RefCounted<MyFoo>; is needed, because base::RefCounted will call delete static_cast<const T*>(this); when released. RefCountedThreadSafe A thread-safe variant of RefCounted<T> template < classT, typename Traits = DefaultRefCountedThreadSafeTraits<T> > classRefCountedThreadSafe; classMyFoo : public base::RefCountedThreadSafe<MyFoo> { private: friend classbase::RefCountedThreadSafe<MyFoo>; }; RefCountedData A thread-safe wrapper for some piece of data so we can place other things in scoped_refptrs. template<typename T> classRefCountedData : public base::RefCountedThreadSafe< base::RefCountedData<T> > { public: RefCountedData() : data() {} RefCountedData(const T& in_value) : data(in_value) {} T data; private: friend classbase::RefCountedThreadSafe<base::RefCountedData<T> >; ~RefCountedData() {} }; scoped_refptrs< RefCountedData<std::string> > spRef = new RefCountedData<std::string>("my.test"); scoped_refptr A smart pointer class for reference counted objects. Use this class instead of ...

The 13 Most Memorable Quotes From Steve Jobs

Today is the two year anniversary of Steve Jobs’s death. He was an iconoclast and often polarizing, but never afraid to tell you exactly what he thought, whether it was during a public speech or a private conversation. Wired and the Wall Street Journal shared some great roundups of their favorite Steve Jobs quotes when his failing health required him to step down as CEO of Apple. We selected a few that were especially awesome. The 13 Most Memorable Quotes From Steve Jobs Incredible words from an incredible businessman, designer, and fellow human. On computers “It takes these very simple-minded instructions—‘Go fetch a number, add it to this number, put the result there, perceive if it’s greater than this other number’––but executes them at a rate of, le ...

curl工具使用

本文介绍下curl的基本使用方法。 下载curl 在主页上 http://curl.haxx.se/ 下载curl压缩包,解压后可以看到几个文件夹:docs(参考文档)、lib(libcurl库源码)、src(curl命令行工具源码)。 curl命令行工具 抓取网页内容 -o:(小写o,或者 –output) curl http://www.baidu.com -o baidu.htm # 还支持参数匹配,将生成 file_baidu.htm 和 file_taobao.htm curl http://www.{baidu,taobao}.com -o "file_#1.htm" 下载文 ...

C++11 多线程

C++11对多线程有了直接的支持,这对于跨平台的统一的线程管理和使用是个福音。 C++11多线程库提供了std::thread类,用于创建和管理线程,还为共享资源的竞态问题提供了互斥量(mutex)、锁、事件通知的条件变量(condition variable)和获取异步调用的返回值(future)等。 std::thread <thread> 构造函数: thread(); th ...