文章目录
前言
本文主要讲解了线程同步的必要性,讲解了
互斥量,读写锁,条件变量三大部分
涉及函数
pthread_mutex_init pthread_mutex_destroy pthread_mutex_lock
pthread_mutex_trylock pthread_mutex_unlock pthread_rwlock_init
pthread_rwlock_destroy pthread_rwlock_rdlock pthread_rwlock_tryrdlock pthread_rwlock_wrlock
pthread_rwlock_trywrlock pthread_rwlock_unlock
pthread_cond_init pthread_cond_destroy pthread_cond_wait
pthread_cond_timedwait pthread_cond_broadcast
pthread_cond_signal
一、互斥量
1.为什么要使用互斥量?
多线程之间的通信是可以通过全局变量来实现的,这样极大的方便线程之间的通信的同时,也会产生新的问题。
当多线程共享相同的内存时,需要每一个线程看到相同的内存“视图“。当一个线程更改变量时,而其它线程也可以读取或者修改这个变量,那么这时对于同一个变量就很可能会出现数据冲突,这时就需要对这些线程同步,确保他们不会访问到无效变量。
在变量修改时间大于一个存储器访问周期的处理器结构中,当存储器的读和写这两个周期交叉时,这种潜在的不一致性就会出现。当然这与处理器相关,但是在可移植的程序中并不能对处理器做出任何假设,因此不管处理器如何,都要进行线程同步。
在上图这个例子中,线程1修改变量i的同时,线程2正在读取变量,假如我们在变量修改时间大于存储器访问周期的处理器下,那么线程2读取到的是还未修改的变量,那么i最后的结果是7,不是我们预期的8。当然上面这幅图仅仅是对于线程操作的表面描述,并没有准确的描述CPU的时间上的具体动作,因此上图只可用来表现线程同步和互斥量使用的必要性,不能用来学习CPU的具体动作。
2.Eg:多线程开发中的数据冲突实例
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
//编译程序需要用链接库
//gcc -lpthread xxx.c -o xxx
//xxx.c是编写的C语言源文件名
//xxx是你想要生成的可执行文件名
//执行效果:
//具体的效果因人而异
//但是会出现同时打印一个结构体三个成员变量
//发现有时候他们三个的值会出现不同
//分析
//明明我们赋值的时候是三个成员变量赋相同值
//但是会打印处不同值,这就说明了对于全局变量i,别的线程也在改变
//因此我们需要对线程进行同步
struct student{
int id;
int age;
int name;
}stu;
int i=1;
void *thread_fun1(void* arg)
{
while(1)
{
stu.id=i;
stu.age=i;
stu.name=i;
i++;
if(stu.id!=stu.age||stu.id!=stu.name||stu.age!=stu.name)
{
printf(“%d %d %d \n”,stu.id,stu.name,stu.age);
break;
}
}
return (void*)0;
}
void *thread_fun2(void* arg)
{
while(1)
{
stu.id=i;
stu.age=i;
stu.name=i;
if(stu.id!=stu.age||stu.id!=stu.name||stu.age!=stu.name)
{
printf(“%d %d %d \n”,stu.id,stu.name,stu.age);
break;
}
i++;
}
return (void*)0;
}
int main()
{
pthread_t tid1,tid2;
int err;
err=pthread_create(&tid1,NULL,thread_fun1,NULL);
if(err!=0)
{
printf(“create new thread1 failed\n”);
return 0;
}
err=pthread_create(&tid2,NULL,thread_fun2,NULL);
if(err!=0)
{
printf(“create new thread2 failed\n”);
return 0;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
3.互斥量
1.概念与理解
为了让线程访问数据不产生冲突,这就要对变量加锁,使得同一时刻只有一个线程可以访问变量。互斥量的本质就是锁,访问共享资源前对互斥量加锁,访问完成后解锁。这个锁不是锁着冲突变量,而是锁住了一个线程的一段执行部分,该部分会涉及公共变量的访问,修改,写入等等可能引发线程之间数据冲突的操作。
当互斥量加锁以后,其它需要访问该互斥量的线程都将阻塞。
当互斥量解锁以后,所有因为这个互斥量阻塞的线程都将变成就绪态,第一个获得CPU的线程会获得互斥量,变为运行态,而其它线程继续变为阻塞,在这种方式下访问互斥量每次只有一个线程向前执行。
2.Linux下的互斥量
互斥量用pthread_mutex_t类型的数据表示,用如下命令查看:
vim /usr/include/bits/pthreadtypes.h
在使用之前需要对互斥量初始化
初始化的方法如下:
1.如果是动态分配的互斥量,可以调用pthread_mutex_init()函数初始化
2.如果是静态分配的互斥量,还可以把它置为常量PTHREAD_MUTEX_INITIALIZER
3.动态分配的互斥量在释放内存之前需要调用pthread_mutex_destroy()
4.相关函数
int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);
//第一个参数是要初始化的互斥量,第二个参数是互斥量属性,默认为NULL
int pthread_mutex_destroy(pthread_mutex_t *mutex);
//参数是要销毁的互斥量
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZE;
//静态分配互斥量且初始化操作
//加锁函数
int pthread_mutex_lock(pthread_mutex_t *mutex);
//成功返回0,失败返回错误码。如果互斥量已经被锁住,那么将导致线程的拥塞
int pthread_mutex_trylock(pthread_mutex_t *mutex);
//成功返回0,失败返回错误码。如果互斥量已经被锁住,不会导致线程拥塞
//解锁函数
int pthread_mutex_unlock(pthread_mutex_t *mutex);
//成功返回0,失败返回错误码
加锁解锁函数的具体细节可以用如下命令查看
man pthread_mutex_unlock
头文件都是:#include<pthread.h>
5.Eg:互斥量实例
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
//编译程序需要用链接库
//gcc -lpthread xxx.c -o xxx
//xxx.c是编写的C语言源文件名
//xxx是你想要生成的可执行文件名
//执行效果:
//不会打印任何东西
//分析
//对比之前没有加锁的相同的程序
//加锁后可以实现结构体三个元素的同步
struct student{
int id;
int age;
int name;
}stu;
int i=1;
pthread_mutex_t mutex;
void *thread_fun1(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
stu.id=i;
stu.age=i;
stu.name=i;
i++;
if(stu.id!=stu.age||stu.id!=stu.name||stu.age!=stu.name)
{
printf(“%d %d %d \n”,stu.id,stu.name,stu.age);
break;
}
pthread_mutex_unlock(&mutex);//被锁起来的代码段都涉及i和结构体的读写操作
}
return (void*)0;
}
void *thread_fun2(void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
stu.id=i;
stu.age=i;
stu.name=i;
if(stu.id!=stu.age||stu.id!=stu.name||stu.age!=stu.name)
{
printf(“%d %d %d \n”,stu.id,stu.name,stu.age);
break;
}
i++;
pthread_mutex_unlock(&mutex);//被锁起来的代码段都涉及i和结构体的读写操作
}
return (void*)0;
}
int main()
{
pthread_t tid1,tid2;
int err;
err=pthread_mutex_init(mutex,NULL);
if(err!=0)
{
printf(“init mutex failed\n”);
return 0;
}
err=pthread_create(&tid1,NULL,thread_fun1,NULL);
if(err!=0)
{
printf(“create new thread1 failed\n”);
return 0;
}
err=pthread_create(&tid2,NULL,thread_fun2,NULL);
if(err!=0)
{
printf(“create new thread2 failed\n”);
return 0;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
二、读写锁
1.读写锁
读写锁与互斥量类似,不过读写锁有更高的并行性。互斥量要么加锁要么不加锁,而且同时只允许一个线程对其加锁。对于一个变量的读取,完全可以多个线程同时操作。
pthread_rwlock_t rwlock;
是读写锁的声明语句
读写锁有三种状态,读模式下加锁,写模式下不加锁与不加锁。一次只有一个线程可以占有写模式下的读写锁,但是多个线程可以占用读模式下的读写锁
1.读写锁在写加锁状态时,在它被解锁之前,所有试图对这个锁加锁的线程都会阻塞。
2.读写锁在读加锁状态时,所有试图以读模式对其加锁的线程都会获得允许
3.读写锁在读加锁状态时,所有试图以写模式对其加锁的线程,会阻塞到所有线程释放锁
读写锁以读模式加锁时,如果有线程试图以写模式对其加锁,那么读写锁会阻塞随后的读模式锁请求。这样可以避免读锁长期占用,而写锁达不到请求。
根据上面的读写锁的特点,可以发现读写锁非常适合对数据读次数大于写次数的程序,当它以读模式锁住时,是以共享方式锁住;当它以写模式锁住时,是以独占有的模式锁住
2.读写锁函数
int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
//读写锁在使用之前必须用上述函数初始化
int pthread_rwlock_destroy(pthraed_rwlock_t *rwlock);
//读写锁使用完需要销毁
int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
//读模式加锁
int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
//读模式试图加锁,不会阻塞
int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
//写模式加锁
int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
//写模式试图枷锁,不会阻塞
int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
//解锁
上述函数都是成功返回0,失败返回错误码
3.Eg:读写锁读状态共享实例
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
//编译程序需要用链接库
//gcc -lpthread xxx.c -o xxx
//xxx.c是编写的C语言源文件名
//xxx是你想要生成的可执行文件名
//执行效果:
//thread 2 print num 0
//thread 1 print num 0
//thread 2 over
//thread 1 over
//分析
//打印num的两个语句基本同时执行
//说明读写锁的读锁是共享的
int num=0;
pthread_rwlock_t rwlock;
void *thread_fun1(void* arg)
{
int err;
pthread_rwlock_rdlock(&rwlock);
printf(“thread 1 print num %d\n”,num);
sleep(5);
printf(“thread 1 over\n”);
pthread_rwlock_unlock(&rwlock);
return (void *)1;
}
void *thread_fun2(void* arg)
{
int err;
pthread_rwlock_rdlock(&rwlock);
printf(“thread 2 print num %d\n”,num);
sleep(5);
printf(“thread 2 over\n”);
pthread_rwlock_unlock(&rwlock);
return (void *)1;
}
int main()
{
pthread_t tid1,tid2;
int err;
err=pthread_rwlock_init(&rwlock,NULL);
if(err!=0)
{
printf(“init rwlock failed\n”);
return 0;
}
err=pthread_create(&tid1,NULL,thread_fun1,NULL);
if(err!=0)
{
printf(“create new thread1 failed\n”);
return 0;
}
err=pthread_create(&tid2,NULL,thread_fun2,NULL);
if(err!=0)
{
printf(“create new thread2 failed\n”);
return 0;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_rwlock_destroy(&rwlock);
return 0;
}
4.Eg:读写锁写状态独占实例
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
//编译程序需要用链接库
//gcc -lpthread xxx.c -o xxx
//xxx.c是编写的C语言源文件名
//xxx是你想要生成的可执行文件名
//执行效果:
//thread 2 print num 0
//thread 2 over
//thread 1 print num 0
//thread 1 over
//分析
//线程1和2的打印语句都是分别执行的,说明写锁回独占CPU,其它线程阻塞
int num=0;
pthread_rwlock_t rwlock;
void *thread_fun1(void* arg)
{
int err;
pthread_rwlock_wrlock(&rwlock);
printf(“thread 1 print num %d\n”,num);
sleep(5);
printf(“thread 1 over\n”);
pthread_rwlock_unlock(&rwlock);
return (void *)1;
}
void *thread_fun2(void* arg)
{
int err;
pthread_rwlock_wrlock(&rwlock);
printf(“thread 2 print num %d\n”,num);
sleep(5);
printf(“thread 2 over\n”);
pthread_rwlock_unlock(&rwlock);
return (void *)1;
}
int main()
{
pthread_t tid1,tid2;
int err;
err=pthread_rwlock_init(&rwlock,NULL);
if(err!=0)
{
printf(“init rwlock failed\n”);
return 0;
}
err=pthread_create(&tid1,NULL,thread_fun1,NULL);
if(err!=0)
{
printf(“create new thread1 failed\n”);
return 0;
}
err=pthread_create(&tid2,NULL,thread_fun2,NULL);
if(err!=0)
{
printf(“create new thread2 failed\n”);
return 0;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_rwlock_destroy(&rwlock);
return 0;
}
三、条件变量
1.为什么需要条件变量?
当互斥量被锁住以后发现当前线程还是无法完成自己的操作,那么它应该释放互斥量,让其它线程工作。
那么线程如何知道自己无法完成任务而释放互斥量,这就需要一种机制
1.可以采用轮询方式,不停的查询需要的条件
2.让系统来帮你查询条件,使用条件变量pthread_cond_t cond;
2.相关函数
条件变量使用之前需要初始化
pthread_cond_t cond=PTHREAD_COND_INITIALIZE;
int pthread_cond_init(pthread_cond_t *restrict cond,const pthread_condattr_t *restrict attr);
//默认属性为NULL
//条件变量使用完成后需要销毁
int pthread_cond_destroy(pthread_cond_t *cond);
//条件变量使用需要配合互斥量
int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);
1.使用pthread_cond_wait等待条件变为真。传递给pthread_cond_wait的互斥量对条件进行保护,调用者把锁住的互斥量传递给函数。
2.这个函数将线程放到等待条件的线程列表上,然后对互斥量进行解锁,这是个整体的且同时的操作。当条件满足时这个函数返回,返回以后继续对互斥量加锁。
int pthread_cond_timedwait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,const struct timespec *restrict abstime);
1.这个函数与pthraed_cond_wait类似,就是多了一个参数abstime,如果到了指定的时间条件还不满足,那么就函数直接返回,返回以后继续对互斥量加锁。。时间用下面的结构体来表示,是Linux系统下表示时间的统一方法。
struct timespec{
time_t tv_sec;
long tv_nsec;
};
注意,这里的时间是相对时间。如果你要等待3分钟,就要把当前时间加上3分钟然后转换到timespec,而不是直接将3分钟转换到timespec
当条件满足时,需要唤醒等待条件的线程
int pthread_cond_broadcast(pthread_cond_)t *cond);
//唤醒等待条件的所有线程
int pthread_cond_signal(pthread_cond_t *cond);
//至少唤醒等待条件的某一个线程,也可以唤醒多个
一定要在条件改变以后再唤醒线程
3.Eg:条件变量的使用
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
//编译程序需要用链接库
//gcc -lpthread xxx.c -o xxx
//xxx.c是编写的C语言源文件名
//xxx是你想要生成的可执行文件名
#define BUFFER_SIZE 5//产品库存大小
#define PRODUCT_CNT 30//产品生产总数
struct product_cons
{
int buffer[BUFFER_SIZE];//生产产品值
pthread_mutex_t lock;//互斥锁 volatile int
pthread_cond_t notempty;//非空
int readpos;//读位置
int writepos;//写位置
pthread_cond_t notfull;//非满
}buffer;
void init(struct product_cons *p)
{
Pthread_mutex_init(&p->lock,NULL);
Pthread_cond_init(&p->notempty,NULL);
Pthread_cond_init(&p->notfull,NULL);
p->readpos=0;
p->writepos=0;
}
void init(struct product_cons *p)
{
Pthread_mutex_destroy(&p->lock,NULL);
Pthread_cond_destroy (&p->notempty,NULL);
Pthread_cond_destroy (&p->notfull,NULL);
p->readpos=0;
p->writepos=0;
}
//存储一个数据到buffer
void put(struct product_cons *p,int data)
{
pthread_mutex_lock(&p->lock);
if((p->writepos+1)%BUFFER_SIZE==p->readpos)//这里是简化的判断非满的条件,并不完全正确
{
printf(“producer wait for not full\n”);
pthread_cond_wait(&p->notfull,&p->lock);
}
p->buffer[p->writepos]=data;
p->writepos++;
if(p->write>=BUFFER_SIZE)
p->writepos=0;
pthread_cond_signal(&p->notempty);
pthraed_mutex_unlcok(&p->lock);
}
//读,从buffer里面移除一个数据
int get(struct product_cons *p)
{
int data;
pthread_mutex_lock(&p->lock);
if(p->readpos==p->writepos)
{
printf(“consumer wait for not empty\n”);
pthread_cond_wait(&p->notempty,&p->lock);
}
data=p->buffer[p->readpos];
p->readpos++;
if(p->readpos>=BUFFER_SIZE)
p->readpos=0;
pthread_cond_signal(&p->notfull);
pthread_mutex_unlock(&p->lock);
return data;
}
void *product(void* data)//子线程---生产
{
int n;
for(n=1;n<=50;++n)
{
sleep(1);
printf(“put the %d product …\n”,n);
put(&buffer,n);
printf(“put the %d product success\n”,n);
}
printf(“producer stopped\n”);
return NULL;
}
void *consumer(void* data)//子线程---消费
{
static int cnt=0;
int num;
while(1)
{
sleep(2);
printf(“get product …\n”);
num=get(&buffer);
printf(“get the %d product success\n”,num);
if(++cnt==PRODUCT_CNT)
break;
}
printf(“consumer stopped\n”);
return NULL;
}
int main(int argc,char *argv[])
{
pthread_t tid1,tid2;
int err;
void* rval;
init(&buffer);
err=pthread_create(&tid1,NULL,product ,NULL);
if(err!=0)
{
printf(“create new thread1 failed\n”);
return 0;
}
err=pthread_create(&tid2,NULL,consumer,NULL);
if(err!=0)
{
printf(“create new thread2 failed\n”);
return 0;
}
pthread_join(tid1,&rval);
pthread_join(tid2,&rval);
finish(&buffer);
return 0;
}
总结
本篇是Linux多线程开发基础篇的第一部分,之后会有更多的内容。
讲解不清晰错误的地方请大家包容指正。
上一篇: Linux—多线程编程(二)—多线程的控制