易截截图软件、单文件、免安装、纯绿色、仅160KB

linux api笔记(6):线程(四) 线程私有数据

本文将描述线程的一个比较重要的一方面:线程私有数据,如下代码:
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
pthread_key_t kKey = 0;
void * ThreadProc(void* arg)
{
char* a = (char*)(arg);
sleep(2);
pthread_setspecific(kKey, a);
sleep(1);
char* str = (char*)pthread_getspecific(kKey);
printf("thread: %s\n", str);
}
int main()
{
pthread_t thread_handle1 = 0;
pthread_t thread_handle2 = 0;
char a[] = {"i am A"};
char b[] = {"i am B"};
pthread_create(&thread_handle1, NULL, ThreadProc, a);
pthread_key_create(&kKey, NULL);
pthread_create(&thread_handle2, NULL, ThreadProc, b);
void* out1 = NULL;
void* out2 = NULL;
pthread_join(thread_handle1, &out1);
pthread_join(thread_handle2, &out2);
return 0;
}
使用线程私有数据的步骤:
1)使用pthread_key_create分配一个线程私有数据的key,这里需要注意的是当我们调用了这个函数
之后进程中所有的线程都可以使用这个key,并且通过这个key获取到的私有数据是互不相同的,比如线程
A通过key设置了数据D,但线程B并没有设置数据,那么A通过key获取的数据当然是D,而B获取的是一个
空的值。另外需要注意的是不管线程是在pthread_key_create调用之前或之后产生,它都能够在函数调用
之后使用这个key。
2)使用pthread_setspecific函数将key和一个线程私有数据绑定。
3)通过pthread_getspecific函数和key获取到这个线程的私有数据。
我一直觉得线程私有数据策略很好用,但考虑到使用过程中需要进行“系统调用”(pthread_getspecific是系统调用吗?),
如果比较频繁地调用这个函数的话说不定会使程序的性能下降,但看了man文档中的一句话后这个中顾虑稍微减轻,尽管还是有疑问:
“the function to pthread_getspecific()  has  been  designed  to  favor speed and simplicity over error reporting”
上面说它的速度已经被设计地很快了。


相关文档:

Linux下配置NFS服务

  1.安装包 
             # apt-get install nfs-kernel-server
  2.编辑配置文件
             # vim /etc/exports
    输入  /home/myhome/work/ ......

linux精华命令

1,用ls只列出目录 ls -F | grep /$
2.查看进程
按内存从大到小排列
ps -e   -o "%C   : %p : %z : %a"|sort -k5 -nr
3.按cpu利用率从大到小排列
ps -e   -o "%C   : %p : %z : %a"|sort   -nr
4.打印说cache里的URL
grep -r -a   jpg /data/cache/* | ......

Linux makefile 教程 非常详细,且易懂

 最近在学习Linux下的C编程,买了一本叫《Linux环境下的C编程指南》读到makefile就越看越迷糊,可能是我的理解能不行。
            于是google到了以下这篇文章。通俗易懂。然后把它贴出来,方便学习。
        & ......

Linux下 zip 和 unzip的用法

     zip命令的基本用法是:zip [参数] [文件1] [文件2]
      简单的例子:
      把本目录下的test文件打包成test.zip文件:zip test.zip test/* ,如果在文件中用绝对的路径,那么在压缩文件中也是绝对路径。就是说,如果你 zip test.zip /hom ......

linux api笔记(4):线程(二)

这一节我们来看看其他线程函数:
int pthread_tryjoin_np(pthread_t thread_handle, void ** thread_return);
int pthread_timedjoin_np (pthread_t thread_handle, void **thread_return, __const struct timespec *abstime);
pthread_tryjoin_np会可以用来判断thread_handle指向的线程是否已经中止,如果没有则*thre ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号