论坛首页 编程语言技术论坛

Linux C中也有“ThreadLocal”

浏览 7834 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-05-29  
C
现在在看Linux开发的书,接触到了多线程开发这一块,惊奇的发现用C写多线程程序,也有线程

内部变量的概念呢,甚至调用的接口和Java中的ThreadLocal非常像。

 1.
 extern int pthread_key_create ((pthread_key_t *__key, void (*__destr_function) (void *)));
  先使用该方法创建一个线程内的Key,且绑定一个函数在线程结束时回收Key对于的空间

2.
  extern int pthread_setspecific __P ((pthread_key_t __key,__const void *__pointer));
  将线程数据和一个键绑定在一起

3.extern void *pthread_getspecific __P ((pthread_key_t __key));
  获得线程数据

4.pthread_key_delete
  删除Key及其对应的线程数据

看来编程语言都是相通的,果真不假啊
   发表时间:2008-05-30  
也可以利用编译器扩展,VC里面有一个,关键字我忘了,gcc里面有__thread。
0 请登录后投票
   发表时间:2008-06-23  
到,这个是os决定的,和语言有什么关系?
0 请登录后投票
   发表时间:2008-06-23  
那是系统调用啊
Java只能在支持多线程的操作系统中多线程 嘿嘿
0 请登录后投票
   发表时间:2008-07-02  
threadlocal只是一个用thread id做key的hashmap而已
0 请登录后投票
   发表时间:2008-07-03  
这是操作系统支持的,非编程语言支持。
0 请登录后投票
   发表时间:2008-07-03  
ruby也有.
引用
Thread#[]

Attribute Reference---Returns the value of a thread-local variable
using either a symbol or a string name. If the specified variable
does not exist, returns +nil+.

比如
Thread.current[:name] = "B"


七猫 写道
这是操作系统支持的,非编程语言支持。

证据是?
0 请登录后投票
   发表时间:2008-07-03  
java在linux中是GreenThread而不是OS Thread吧?
0 请登录后投票
   发表时间:2008-07-05  
这个东西属于thread specific storage设计模式,在schimdt的POSA volumn 2 中专门有提及,在schimdt的主页也有该paper下,因此不限于语言
0 请登录后投票
   发表时间:2008-07-05  
刚刚看到boost::asio里有一段用posix API 来实现thread specific storage的代码,当然win API 也是一样
template <typename T>
class posix_tss_ptr  : private noncopyable
{
public:
  // Constructor.
  posix_tss_ptr()
  {
    int error = ::pthread_key_create(&tss_key_, 0);
    if (error != 0)
    {
      asio::system_error e(
          asio::error_code(error,
            asio::error::get_system_category()),
          "tss");
      boost::throw_exception(e);
    }
  }

  // Destructor.
  ~posix_tss_ptr()
  {
    ::pthread_key_delete(tss_key_);
  }

  // Get the value.
  operator T*() const
  {
    return static_cast<T*>(::pthread_getspecific(tss_key_));
  }

  // Set the value.
  void operator=(T* value)
  {
    ::pthread_setspecific(tss_key_, value);
  }

private:
  // Thread-specific storage to allow unlocked access to determine whether a
  // thread is a member of the pool.
  pthread_key_t tss_key_;
};
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics