Monday, July 26, 2010

tbb: Intel® Threading Building Blocks笔记

tbb(Threading Building Blocks)是Intel开发的一个C++模板库, 类似于STL. 其特点是针对对于多核(multi-core)CPU的优化.提高在多线程的环境下程序并发性. tbb提供了多种类似于STL但高度并行的容器类.

安装

Ubuntu:
sudo apt-get install libtbb2 libtbb-dev libtbb-doc
MacOS上:
sudo port install tbb
编译

g++ -ltbb foo.cpp
使用

concurrent_hash_map
此容器是类似于STL中的map的存在. 同std::map一样,concurrent_hash_map为一个从Key类型读取T类型的容器. 为提高并发性,我们需要用accessor或者const_accessor两种不同方式访问此容器的某元素.accessor和const_accessor均为智能指针,其中accessor写和修改访问,会lock相应的key直到访问结束.而const_accessor用于只读方式访问,这样可以同时有多个不同的const_accessor同时指向同一个key.区分不同的访问方式有助于增加程序的并发性.


#include <iostream>
#include <string>
#include <tbb/concurrent_hash_map.h>

using namespace tbb;
using namespace std;
typedef concurrent_hash_map<string,string> CacheTable;

int main() {
    CacheTable cache;

    // insert an element to the map
    CacheTable::accessor a;
    cache.insert(a, s);
    a->second = "value1";
    a.release();
    
    // look for an element in the map
    CacheTable::const_accessor ca;
    if (cache.find(ca, "key1"))
         cout << "the value is " << ca->second << endl;
    else
         cout << "not found" << endl;

    // iterate over the map
    for(CacheTable::const_iterator itr=cache.begin(); itr!=cache.end(); ++itr)
         std::cout << itr->first << " - " << itr->second << std::endl;

}
concurrent_queue
一个类似于stl中queue的存在. 提供包括push(item),pop(item)以及try_pop(item)等等的操作.
下面是对于一个concurrent_queue的iteration操作:
#include <iostream>
typedef concurrent_queue::const_iterator iter;
for(iter i(q.unsafe_begin()); i!=q.unsafe_end(); ++i ) {
   do sth 
}

atomic
如果atomic< your data type> x, 以下操作为原子操作
= x  read the value of x
x =  write the value of x, and return it
x.fetch_and_store(y)  do y=x and return the old value of x
x.fetch_and_add(y)  do x+=y and return the old value of x
x.compare_and_swap(y,z)  if x equals z, then do x=y. In either case, return old value of x

No comments: