之前学习的线程都是采用线程的默认属性,默认属性其实已经可以解决大多数开发时遇到的问题,但是如果我们想要我们的程序性能变得更好,那么就需要设置线程的属性,例如:我么可以设置线程的大小来降低内存的使用,增加最大线程个数
typedef struct
{
int detachstate; //线程的分离状态
int schedpolicy; //线程调度策略
struct sched_param schedparam; //线程的调度参数
int inhertsched; //线程的继承性
int scope; //线程的作用域
size_t guardsize; //线程栈末尾的警戒缓冲区大小
int stackaddr_set; //线程栈的设置
void *stackaddr; //线程栈的位置
size_t stacksize; //线程栈的大小
}
主要结构体成员:
1. 线程分离状态
2. 线程栈大小(默认平均分配)
3. 线程栈警戒缓冲区大小(位于栈的末尾)
属性值不能直接涉资。必须使用相关函数进行操作,初始化的函数为pthread_attr_init,这个函数必须在pthread_create函数之前调用,之后需要用pthread_attr_destory函数来释放资源
线程属性主要包括:作用域、栈尺寸、站地址、优先级、分离状态、调度策略和参数。默认属性为非绑定、非分离、缺省的栈堆、与父进程同样级别的优先级
1. 线程
1.1 线程属性初始化
初始化线程属性
int pthread_attr_init(pthread_attr_t *attr);
成功:0
失败:错误号
销毁线程属性所占用的资源
int pthread_attr_destroy(pthread_attr_t *attr);
成功:0
失败:错误号
1.2 线程的分离状态
线程的分离状态会决定一个线程以什么方式来终结自己
一般会默认非分离状态,这钟情况下,原有线程等待创建的线程结束,只有当pthread_join()函数返回的时候,创建的新线程才算终止,才能释放自己占用的系统资源
分离状态:分离线程没有被其他的线程所等待,自己运行结束了,线程也就终止了,马上会释放系统资源,我们应该根据自己的需要选择适当的分离状态
线程分离状态的函数
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
获取线程属性,分离or非分离
int pthread_attr_getdetachstate(pthread_attr_t *attr, int *detachstate);
参数:
attr:已初始化的线程状态
detachstate: PTHREAD_CREATE_DETACHED(分离线程)
PTHREAD_CREATE_JOINABLE(非分离线程)
例:通过设置线程分离属性,创建分离子线程
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
void *tfn(void *arg)
{
printf("thread: pid = %d, tid = %lu\n", getpid(), pthread_self());
return NULL ;
}
int main(void)
{
pthread_t tid;
pthread_attr_t attr;
int ret=pthread_attr_init(&attr);
if(ret!=0)
{
fprintf(stderr,"attr_init error:%s\n",strerror(ret));
exit(1);
}
ret=pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);//设置线程属性为,分离属性
if(ret!=0)
{
fprintf(stderr, "attr_setdetachstate error:%s\n",strerror(ret));
exit(1);
}
ret = pthread_create(&tid, &attr, tfn, NULL);
if(ret!=0)
{
perror("pthread_create error");
exit(1);
}
ret = pthread_attr_destroy(&attr);
if(ret!=0)
{
fprintf(stderr, "attr_ destroy error:%s\n",strerror(ret));
exit(1);
}
ret=pthread_join(tid, NULL);
printf("thread_join() ret = %d\n",ret);
if(ret!=0)
{
fprintf(stderr, "thread_join error:%s\n",strerror(ret));
exit(1);
}
printf("main: pid = %d, tid = %lu\n", getpid(), pthread_self());
return 0;
}
如果我们设置了一个分离线程,二这个线程又非常快,他会在pthread_crate函数返回之前就终止了,它种植以后就可能看到线程号和系统资源移动到其他的线程使用,这样调用pthread_create的线程旧的岛了错误的线程号,要避免这种情况可以采用一定的同步措施,最简单的方法就是可以在被创建的线程里调用pthread_cond_timewait函数,让这个线程多等一会儿,留出足够的时间让函数pthread_create返回,设置一段等待时间,是在多线程变成里常用的方法,但是注意不要用wait之类的函数,它会使整个进程睡眠,并不能解决线程同步的问题
1.3 线程使用注意事项
1. 主线程退出其他线程不退出,主线程应调用pthread_exit,任何线程调用exit都会导致整个线程组退出
2. 避免僵尸进程
pthread_join 回收
pthread_detache 分离
pthread_create 指定分离属性
被join的线程可能在join函数返回前就释放完自己的所有内存资源,所以不应当返回被回收线程栈中 的值
3.malloc 和mmap申请的内存可以被其他线程释放。
4.应避免在多线程模型中调用fork,除非马上exec, 子进程中只有调用fork的线程存在,其他线程在子进 程中均pthread_exit.
5.信号的复杂语义很难和多线程共存,应避免在多线程引入信号机制。
2. 同步
同步,顾名思义就是同时起步,步调一致,不同的对象,对同步的理解方式各有不同
如:设备同步,是指在两个设备之间规定一个共同的时间参考:
数据库同步,是指让两个或多个数据库内容保持一致,或者按需要部分保持一致:
文件同步,是指让两个或多个文件夹里的文件保持一致。等等。
而在编程中、通信中所说的同步与生活中大家印象中的同步概念略有差异。“同”字应是指协同、协助、 互相配合。主旨在协同步调,按预定的先后次序运行。
2.1 线程同步
同步,即是同步调,对公共区域数据按预定的先后次序访问,防止数据混乱
线程同步,指的是一个线程发出某一功能调用时,在没有得到接过钱,该调用不返回,同时其他线程为了保证数据的一致性,不能调用该功能
举例:内存中100字节,线程T1欲填入全1,线程T2 欲填入全0.但如果T1执行了50个字节失去cpu, T2执 行,会将T1写过的内容覆盖。当T1再次获得cpu继续从失去 cpu的位置向后写入1.当执行结束,内存中 的100字节,既不是全1,也不是全0
产生的现象叫做“与时间有关的错误”(time related)。为了避免这种数据混乱,线程需要同步。
“同步”的目的,是为了避免数据混乱,解决与时间有关的错误。实际上,不仅线程间需要同步,进程 间、信号间等等都需要同步机制。
因此,所有“多个控制流,共同操作一个共享资源”的情况,都需要同步。
2.2 数据混乱的原因
1. 资源共享(独享资源则不会)
2. 调度随机(意味着数据访问会出现竞争)
3. 线程缺乏必要的同步机制
以上3点中,前两点不能改变,欲提高效率,传递数据,资源必须共享。只要共享资源,就一定会出现竞 争。只要存在竞争关系,数据就很容易出现混乱。 所以只能从第三点着手解决。使多个线程在访问共享资源的时候,出现互斥。
3. 互斥量
Liunx中提供了一把互斥锁 mutex(也称互斥量)
每个线程在对资源操作前都会尝试枷锁,成功加锁才能操作,操作结束解锁
资源还是共享的,但是线程间也是竞争的
但是通过锁的方式,就可以将资源的访问变成互斥的操作,而后与时间有关的错误也不会发生
但是,我们需要注意的是:在同一时刻,只有一个线程持有该锁
例如当A线程对某个全局变量加锁访问,B在访问前尝试加锁,拿不到锁,B阻塞。C线程不去加锁,而直接访 问该全局变量,依然能够访问,但会出现数据混乱。 所以,互斥锁实质上是操作系统提供的一把“建议锁”(又称“协同锁”),建议程序中有多线程访问共享资源 的时候使用该机制。但,并没有强制限定。 因此,即使有了mutex,如果有线程不按规则来访问数据,依然会造成数据混乱。
例:父子线程共同使用共享资源stdout,利用sleep造成时间差混乱
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
void *tfn(void *arg)
{
srand(time(NULL));
while(1)
{
printf("hello ");
sleep(rand() % 3);
printf("world\n");
sleep(rand() % 3);
}
return NULL;
}
int main()
{
pthread_t tid;
srand(time(NULL));
pthread_create(&tid, NULL, tfn, NULL);
while(1)
{
printf("HELLO ");
sleep(rand() % 3);
printf("WORLD\n");
sleep(rand() % 3);
}
pthread_join(tid, NULL);
return 0;
}
3.1 主要应用函数
pthread_mutex_init 函数
pthread_mutex_destroy函数
pthread_mutex_lock 函做
pthread_mutex_trylock 函数
pthread_mutex_unlock 函数
以上5个函数的返回值都是:成功返回0,失败返回错误号。
pthread_mutex_t 类型,其本质是一个结构体。 为简化理解,应用时可忽略其实现细节,简单当成 整数看待。 p
thread_mutex_t mutex;变量mutex只有两种取值1、0。
3.2 使用mutex(互斥量、互斥锁)一般步骤
1. pthread_mutex_t mutex 创建锁
2. pthread_mutex_init 初始化
3. pthread_mutex_lock 加锁
4. 范围内共享数据
5. pthread_mutex_unlock 解锁
6. pthread_mutes_destroy 销毁锁
3.3 lock与unlock
lock尝试加锁,如果加锁不成功,线程阻塞,阻塞到持有该互斥量的其他线程解锁为止
unlock主动解锁函数。同时将阻塞在该锁上的所有线程全部唤醒,至于哪个线程先被唤醒,取决于优先级、调度。默认:先阻塞、先唤醒。
例如: T1 T2 T3 T4 使用一把mutex锁。T1加锁成功,其他线程均阻塞,直至T1 解锁。T1解锁后,T2 T3 T4均被唤醒,并自动再次尝试加锁。
可假想mutex锁init 成功初值为1. lock 功能是将mutex--. 而unlock则将mutex++。
3.4 lock和trylock
lock加锁失败会阻塞,等待锁释放。
trylock加锁失败直接返回错误号(如: EBUSY)不阻塞
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t mutex;
void *tfn2(void *arg)
{
srand(time(NULL));
while(1)
{
int ret = pthread_mutex_trylock(&mutex);
if(ret != 0)
{
printf("pthread_mutx_trylock err:%s\n", strerror(ret));
}
else
{
printf("---tfn2()---print ");
sleep(rand() % 3);
printf("to stdout\n");
sleep(rand() % 3);
ret = pthread_mutex_unlock(&mutex);//解锁
if(ret != 0)
{
fprintf(stderr, "pthread_mutex_unlock() error:%s\n", strerror(ret));
}
}
printf("common tfn2()------\n");
sleep(rand() % 3);
}
}
void *tfn(void *arg)
{
srand(time(NULL));
while(1)
{
int ret = pthread_mutex_lock(&mutex);//加锁
if(ret != 0)
{
fprintf(stderr, "pthread_mutex_lock() error:%s\n", strerror(ret));
}
printf("hello ");
sleep(rand() % 3);
printf("world\n");
ret = pthread_mutex_unlock(&mutex);
if(ret != 0)
{
fprintf(stderr, "pthread_mutex_unlock() error:%s\n", strerror(ret));
}
sleep(rand() % 3);
}
return NULL;
}
int main()
{
pthread_t tid1;
pthread_t tid2;
srand(time(NULL));
//初始化,互斥锁
int ret = pthread_mutex_init(&mutex, NULL);
if(ret != 0)
{
fprintf(stderr, "mutex init error:%s\n", strerror(ret));
}
//创建线程1
ret = pthread_create(&tid1, NULL, tfn, NULL);
if(ret != 0)
{
fprintf(stderr, "pthread_create error:%s\n", strerror(ret));
}
//创建线程2
ret = pthread_create(&tid2, NULL, tfn2, NULL);
if(ret != 0)
{
fprintf(stderr, "pthread_create error:%s\n", strerror(ret));
}
while(1)
{
ret = pthread_mutex_lock(&mutex);
if(ret != 0)
{
fprintf(stderr, "pthread_mutex_lock() error:%s\n", strerror(ret));
}
printf("HELLO ");
sleep(rand() % 3);
printf("WORLD\n");
//对加锁成功的共享资源进行解锁
if(ret != 0)
{
fprintf(stderr, "pthread_mutex_unlock() error:%s\n", strerror(ret));
}
sleep(rand() % 3);
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
ret = pthread_mutex_destroy(&mutex);
if(ret != 0)
{
fprintf(stderr, "pthread_mutex_destroy() error:%s\n", strerror(ret));
}
return 0;
}
注意事项: 尽量保证锁的粒度,越小越好。 (访问共享数据前, 加锁。访问结束后,应立即解锁)
互斥锁:本质是结构体,我们可以看做是整数,初值为1 (pthread_mutex_init()函数调用成功) 加锁:--操作,阻塞线程。
解锁:++操作,唤醒阻塞在锁上的线程
try锁:尝试加锁,成功--;失败,继续其他业务功能代码
3.5 死锁
是使用锁不恰当导致的现象
1. 线程试图对同一个互斥量A加锁2次(连续调用pthread_mutex_lock两次级以上)
2.线程1拥有A锁,请求获得B锁;线程2拥有B锁,请求拥有A锁
4. 读写锁
与互斥量类似,但读写锁允许更高的并行性。
其特性为:锁只有一把;写独占,读共享;写锁优先级高;
4.1 读写锁状态
读写锁只有一把,但其具备两种状态:
1.读模式下加锁状态(读锁)。
2.写模式下加锁状态(写锁)。
4.2 读写锁特征
1.读写锁是“写模式加锁”成功时,其他线程尝试加锁都会被阻塞
2.读写锁是“读模式加锁”成功时,其他线程以写模式加锁会阻塞
3.读写锁是“读模式加锁”时,既有试图以写模式枷锁的线程,也有试图以读模式加锁的线程,那么读写锁会阻塞随后读模式锁请求。优先满足写模式锁。读锁、写锁并行阻塞,写锁优先级高
读写锁也叫共享-独占锁
a.当读写锁以读模式锁住时,它是以独占模式锁住的,其他读线程可以读取内容
b.当它以写模式锁住时,它是以独占模式锁住的,其他操作均会被阻塞
读写锁非常适合对数据结构读的次数大于写的情况
4.3 主要应用函数
pthread_rwlock_init 函数
pthread_rwlock_destroy 函数
pthread_rwlock_rdlock 函数
pthread_rwlock_wrlock函数
pthread_rwlock_tryrdlock 函数
pthread_rwlock_trywrlock 函数
pthread_rwlock_unlock函数
以上7个函数的返回值都是,成功返回0,失败直接返 回错误号。
pthread_rwlock_t 类型 用于定义一个读写锁变量
pthread_rwlock_t rwlock;
初始化一把读写锁
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
参1:传读写锁变量
参2:attr表示读写锁属性,通常使用默认值,传NULL即可。
销毁一把读写锁
int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
参1:传读写锁变量
以读方式请求读写锁(简称:请求读锁)
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
参1:传读写锁变量
以写方式请求读写锁(简称:请求写锁)
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
参1:传读写锁变量
解锁
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
参1:传读写锁变量
例子:3个线程不定时写同一全局资源,5个线程不定时读同一个全局资源
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int counter;
pthread_rwlock_t rwlock;
/* 3个线程不定时写同一全局资源,5个线程不定时读同一全局资源*/
void *th_write(void *arg)
{
int t;
int i = (long int)arg;
while (1)
{
pthread_rwlock_wrlock(&rwlock);//以写模式加锁
t = counter;
sleep(1);
printf("=====write %d: %lu: counter=%d ++counter=%d\n", i,
pthread_self(), t, ++counter);
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
return NULL;
}
void *th_read(void *arg)
{
int i = (long int)arg;
while (1)
{
pthread_rwlock_rdlock(&rwlock);//读线程间,读锁共享
printf("----------------------read %d: %lu: %d\n", i, pthread_self(),
counter);
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
return NULL;
}
int main(void)
{
long int i;
pthread_t tid[8];
pthread_rwlock_init(&rwlock, NULL);
for(i=0;i<3;i++)
{
pthread_create(&tid[i], NULL, th_write, (void *)i);
}
for(i=0;i<5;i++)
{
pthread_create(&tid[i+3], NULL, th_read, (void *)i);
}
for(i=0;i<8;i++)
{
pthread_join(tid[i], NULL);
}
pthread_rwlock_destroy(&rwlock);
return 0;
}