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”
上面说它的速度已经被设计地很快了。
相关文档:
前言:目前正在忙于ARM平台的Linux应用程序的开发(其实是刚刚起步学习啦)。底层的东西不用考虑了,开发板子提供了NAND Bootloader,和Linux 2.6的源码,而且都编译好了。自己编译的bootloader可以用,但是Linux编译后,文件很大,暂且就用人家编译的系统,先专心写应用程序 吧。。
正文:要做的任务是,把一块板子上的 ......
[经过安装测试成功的方法from CYBEND ]
第一步:系统与软件的准备
系统版本 redhat enterprise linux 5 ,内核版本 2.6.18
第二步:软件包的准备
httpd软件包:httpd-2.2.8.tar.bz2
mysql软件包从mysql官方网站下载,我选用的是ehel5的rpm包
MySQL-server-community-5.0.51a-0.rhel5.i386.rpm
MySQL-client-community ......
这一节我们来看看其他线程函数:
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 ......
软实时和硬实时,软实时是说违反了程序执行的deadline也不会有致命的错误,而硬实时的deadline是写死的。
很多linux有硬实时的补丁,如MontaVista。
有源晶振和无源晶振,有源的叫osllicator,无源的叫crystal。
uclinux是静态编译的,没有mmu机制。
x86的要选xterm...
serveu假设服务器 + linux用sftp(通过ssh ......