1. 为什么要多线程?
多线程可以提高系统的性能。更方便实现某些程序模型。
2. posix中的一些线程安全函数如下
asctime_r, ctime_r, getgrgid_r,getgrnam_r, getpwnam_r,
getpwuid_r, gmtime_r, localtime_r, rand_r, readdir_r, strtok_r
3. 线程安全和可重入例程的特点
线程安全例程是指这个例程即使被多个线程同时调用也不会产生错误的结果。
通常,可以通过一下三种方法来保证线程安全:
3.1 设计成可重入例程
只使用参数和堆栈的例程。
void test(int *buf) {
int in_buf[20];
buf[0] = in_buf[0];
....
}
3.2 使用线程局部的数据
使用thread specific data或者Thread local Storage技术的函数
3.3 利用锁技术
spinlock, mutex_lock , ...
4. 非线程安全函数的例子
4.1 libc 中的ctime
返回了全局的静态分配的_tmbuf
struct tm _tmbuf;
/* Return the `struct tm' representation of *T in local time. */
struct tm *
localtime (t)
const time_t *t;
{
return __tz_convert (t, 1, &_tmbuf);
}
没有评论:
发表评论