线程特定数据 int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)); int pthread_key_delete(pthread_key_t key); int pthread_setspecific(pthread_key_t key, const void *pointer); void * pthread_getspecific(pthread_key_t key); pthread_onc…
线程概念 在一个程序里的一个执行路线就叫做线程(thread).更准确的定义是:线程是"一个进程内部的控制序列/指令序列"; 一切进程至少有一个执行线程; 进程  VS. 线程  1.进程是资源分配(进程需要参与资源的竞争)的基本单位,而线程是处理器调度(程序执行)的最小单位; 2.线程共享进程数据,但也拥有自己的一部分(非常少O(∩_∩)O~)数据,如线程ID.程序计数器.一组寄存器.堆栈.errno(错误代码).信号状态.优先级等; 3.一个进程内部的线程可以共享资源,如代码段.数…
POSIX线程库 与线程有关的函数构成了一个完整的系列,绝大多数函数的名字都是以"pthread_"开头,要使用这些函数库,要通过引入头文<pthread.h>,而且链接这些线程函数库时要使用编译器命令的"-lpthread"选项[Ubuntu系列系统需要添加的是"-pthread"选项而不是"-lpthread",如Ubuntu 14.04版本,深度Ubuntu等] 1.pthread_create int pt…
初始化/销毁线程属性 int pthread_attr_init(pthread_attr_t *attr); int pthread_attr_destroy(pthread_attr_t *attr); 线程分离属性 int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate); int pthread_attr_setdetachstate(pthread_attr_t *attr, int de…
在单线程程序中.我们常常要用到"全局变量"以实现多个函数间共享数据, 然而在多线程环境下.因为数据空间是共享的.因此全局变量也为全部线程所共同拥有.但有时应用程序设计中有必要提供线程私有的全局变量,仅在某个线程中有效,但却能够跨多个函数訪问.POSIX线程库通过维护一定的数据结构来解决问题.这个些数据称为(Thread-specific-data或 TSD). 相关函数例如以下: int pthread_key_create(pthread_key_t *key, void (*des…
在这个多核时代,如何充分利用每个 CPU 内核是一个绕不开的话题,从需要为成千上万的用户同时提供服务的服务端应用程序,到需要同时打开十几个页面,每个页面都有几十上百个链接的 web 浏览器应用程序,从保持着几 t 甚或几 p 的数据的数据库系统,到手机上的一个有良好用户响应能力的 app,为了充分利用每个 CPU 内核,都会想到是否可以使用多线程技术.这里所说的"充分利用"包含了两个层面的意思,一个是使用到所有的内核,再一个是内核不空闲,不让某个内核长时间处于空闲状态.在 C++98 …
一.posix 线程属性 POSIX 线程库定义了线程属性对象 pthread_attr_t ,它封装了线程的创建者可以访问和修改的线程属性.主要包括如下属性: 1. 作用域(scope) 2. 栈尺寸(stack size) 3. 栈地址(stack address) 4. 优先级(priority) 5. 分离的状态(detached state) 6. 调度策略和参数(scheduling policy and parameters) 线程属性对象可以与一个线程或多个线程相关联.当使用线程…
一线程的本质 二线程模型的引入 三线程特定数据 四关键函数说明 五刨根问底啥原理 六私有数据使用演示样例 七參考文档 一.线程的本质 Linux线程又称轻量进程(LWP),也就说线程本质是用进程之间共享用户空间模拟实现的. 二.线程模型的引入 线程模型引入是为了数据共享,为什么又引入线程私有数据? 有时候想让基于进程的接口适应多线程环境,这时候就须要为每一个线程维护一份私有数据了.最典型的就是errno了. 在维护每一个线程的私有数据的时候,我们可能会想到分配一个保存线程数据的数组,用线程的ID…
举个栗子 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pthread.h> #include <errno.h> #include <string.h> #define ERR_EXIT(m)\ do\ {\ perror(m);\ exit(EXIT_FAILURE);\ })\ t…
muduo库线程特定数据源码文件为ThreadLocal.h //线程本地存储 // Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com) #ifndef MUDUO_BASE_THREADLOCAL_H #define MUDUO_BASE…