易截截图软件、单文件、免安装、纯绿色、仅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篇(一)

最近准备学习一下操作系统原理,于是照例记录一些重要的东西。
1. 操作系统的功能
    从资源管理的角度来看,操作系统的功能一般分为5种:
    1.1 存储管理
          存储管理就是管理计算机有限的内存空间,包括:存储分配、存储安全和 ......

linux 安装Kmplayer播放器


安装Kmplayer播放器
(作者/l4nneret)为了能在 Linux 下也能播放多媒体文件,于是安装据称很强悍的 Kmplayer 播放器。过程如下:在 http://www.mplayerhq.hu/MPlayer/ 这里看到 Kmplayer 的主程序已经更新到了 1.0rc2 版。
下载主程序:MPlayer-1.0rc2.tar.bz2
两个解码包:all-20071007.tar.bz2 和 windows-all-2007 ......

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 ......

想起来的一些关于linux的一些知识

软实时和硬实时,软实时是说违反了程序执行的deadline也不会有致命的错误,而硬实时的deadline是写死的。
很多linux有硬实时的补丁,如MontaVista。
有源晶振和无源晶振,有源的叫osllicator,无源的叫crystal。
 uclinux是静态编译的,没有mmu机制。
x86的要选xterm...
serveu假设服务器 + linux用sftp(通过ssh ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号