1.线程概述(与进程的区别及线程的优势)
什么是线程?
在一个程序里的一个执行路线就叫做线程(thread)。更准确的定义是:线程是“一个进程内部的控制序列”。
一切进程至少都有一个执行线程。
线程是进程内部的一条执行序列或执行路径,即一个可调度的实体。一个进程可以包含多条线程
在Linux下进程是资源分配的基本单位,线程是cpu调度的基本单位
1.1 线程的优点
创建一个新线程的代价要比创建一个新进程小得多
与进程之间的切换相比,线程之间的切换需要OS的工作量更少
线程占用的资源比进程少得多
2.Linux线程控制:pthread线程库
首先要强调一点:pthread库并不是系统库,而是Linux下为了模拟线程而采用的第三方库。本质是封装了对于轻量级进程的某些操作。
链接这些线程函数库时要使用编译器命令的“-lpthread”选项
接口:
pthread_create()
pthread_join()
pthread_cancel()
pthread_exit()
pthread_self()
2.1线程的创建
功能: 创建一个新的线程
原型`int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void * (start_routine)(void), void *arg);
`4个参数
- thread:返回线程ID,这是进程地址空间的共享区的地址
- attr:设置线程的属性,attr为NULL表示使用默认属性
- start_routine:是个函数地址,线程启动后要执行的函数
- arg:传给线程启动函数的参数,如果需要传入多个参数,可以用结构体封装
返回值: 成功返回0;失败返回错误码
创建线程
#include <stdio.h>
#include <pthread.h>
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//void *(*start_routine) (void *), void *arg);
void *func1(void *arg){
printf("t1 : thread ID is : %ld\n ",pthread_self());//打印线程的id
printf("t1 : pramm = %d \n", *((int *)arg));
}
int main(){
pthread_t t1;
int pramm=100;
int ret= pthread_create(&t1, NULL ,func1 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret == 0 ){
printf("thread success\n");
}
printf("main : %ld\n",pthread_self());
// while(1);
int ret1 = pthread_join(t1, NULL);
return 0 ;
}
~
2.2 线程等待
为什么要等待?
已经退出的线程,其空间没有被释放,仍然在进程的地址空间内。
创建新的线程不会复用刚才退出线程的地址空间。
功能:等待线程结束
原型
int pthread_join(pthread_t thread, void **value_ptr);
参数
- thread:线程ID
- value_ptr:它指向一个指针,后者指向线程的返回值
- 返回值成功返回0;失败返回错误码
调用该函数的线程将挂起等待,直到id为thread的线程终止。thread线程以不同的方法终止,通过pthread_join得到的
终止状态是不同的,总结如下:
- 如果thread线程通过return返回,value_ ptr所指向的单元里存放的是thread线程函数的返回值。
- 如果thread线程被别的线程调用pthread_ cancel异常终掉,value_ ptr所指向的单元里存放的是常数PTHREAD_CANCELED。
- 如果thread线程是自己调用pthread_exit终止的,value_ptr所指向的单元存放的是传给 pthread_exit的参数。
- 如果对thread线程的终止状态不感兴趣,可以传NULL给value_ ptr参数。
#include <stdio.h>
#include <pthread.h>
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//void *(*start_routine) (void *), void *arg);
void *func1(void *arg){
static int num=10;
printf("t1 : thread ID is : %ld\n ",pthread_self());//打印线程的id
printf("t1 : pramm = %d \n", *((int *)arg));
// void pthread_exit(void *retval);
pthread_exit(&num);
}
int main(){
pthread_t t1;
int pramm=100;
int *pre=NULL;
int ret= pthread_create(&t1, NULL ,func1 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret == 0 ){
printf("thread success\n");
}
printf("main : %ld\n",pthread_self());
// while(1);
// int pthread_join(pthread_t thread, void **retval);
int ret1 = pthread_join(t1,(void **)&pre);
printf("main : p = %d \n",*pre);
return 0 ;
}
2.3获取线程ID
pthread_ create函数会产生一个线程ID,存放在第一个参数指向的地址中。该线程ID和前面说的线程ID不是一回事。
前面讲的线程ID属于进程调度的范畴。因为线程是轻量级进程,是操作系统调度器的最小单位,所以需要一个数值来唯一表示该线程。
pthread_ create函数第一个参数指向一个虚拟内存单元,该内存单元的地址即为新创建线程的线程ID,属于NPTL线程库的范畴。线程库的后续操作,就是根据该线程ID来操作线程的。
线程库NPTL提供了pthread_ self函数,可以获得线程自身的ID:
pthread_t pthread_self(void);
2.4线程共享内存
代码实现:
#include <stdio.h>
#include <pthread.h>
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//void *(*start_routine) (void *), void *arg);
void *func1(void *arg){
static char *str="this is exit";
printf("t1 : thread ID is : %ld\n ",pthread_self());//打印线程的id
printf("t1 : pramm = %d \n", *((int *)arg));
// void pthread_exit(void *retval);
pthread_exit(str);
}
void *func2(void *arg){
static char *str22="this is exit";
printf("t2 : thread ID is : %ld\n ",pthread_self());//打印线程的id
printf("t2 : pramm = %d \n", *((int *)arg));
// void pthread_exit(void *retval);
pthread_exit(str22);
}
int main(){
pthread_t t1;
pthread_t t2;
int pramm=100;
char *str=NULL;
char *str2=NULL;
int ret= pthread_create(&t1, NULL ,func1 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret == 0 ){
printf("thread1 success\n");
}
int ret2= pthread_create(&t2, NULL ,func2 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret2 == 0 ){
printf("thread2 success\n");
}
printf("main : %ld\n",pthread_self());
// while(1);
// int pthread_join(pthread_t thread, void **retval);
pthread_join(t1,(void **)&str);
pthread_join(t2,(void **)&str2);
printf("main : str = %s \n",str);
return 0 ;
}
#include <stdio.h>
#include <pthread.h>
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//void *(*start_routine) (void *), void *arg);
int cnt=0;
void *func1(void *arg){
//printf("t1 : thread ID is : %ld\n ",pthread_self());//打印线程1的id
//printf("t1 : pramm = %d \n", *((int *)arg));
// void pthread_exit(void *retval);
while(1){
printf("t1 : %d\n",cnt++);
sleep(1);//睡眠一秒,防止线程1一直占用内存
if(cnt == 3){
pthread_exit(NULL);
}
}
}
void *func2(void *arg){
//printf("t2 : thread ID is : %ld\n ",pthread_self());//打印线程的id
// printf("t2 : pramm = %d \n", *((int *)arg));
// void pthread_exit(void *retval);
while(1){
printf("t2 : %d\n",cnt++);
sleep(1);//睡眠一秒,防止线程2一直占用内存
}
}
int main(){
pthread_t t1;
pthread_t t2;
int pramm=100;
int ret= pthread_create(&t1, NULL ,func1 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret == 0 ){
// printf("thread1 success\n");
}
int ret2= pthread_create(&t2, NULL ,func2 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret2 == 0 ){
// printf("thread2 success\n");
}
while(1){
printf("main : %d\n",cnt++);
sleep(1);//睡眠一秒,防止main一直占用内存
}
// printf("main : %ld\n",pthread_self());
// int pthread_join(pthread_t thread, void **retval);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
// printf("main : str = %s \n",*str);
return 0 ;
}
3.互斥锁相关API
互斥量(mutex)从本质上来说是一把锁,在访问共享资源前对互斥量进行设置(加锁),在访问完成后释放(解锁)互斥量。对互斥量进行加锁后,任何其他试图再次对互斥量加锁的线程将会被阻塞直到当前线程释放该互斥锁。如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上的阻塞线程都会变成可运行状态,第一个变为可运行状态的线程可以对互斥量加锁,其他线程将会看到互斥锁依然被锁住,只能回去等待它重新变为可用。在这种方式下,每次只有一个线程可以向前运行。
在设计时需要规定所有的线程必须遵守相同的数据访问规则。只有这样,互斥机制才能正常工作。操作系统并不会做数据访问的串行化。如果允许其中的某个线程在没有得到锁的情况下也可以访问共享资源,那么即使其它的线程在使用共享资源前都获取了锁,也还是会出现数据不一致的问题。
互斥变量用pthread_mutex_t数据类型表示。在使用互斥变量前必须对它进行初始化,可以把它置为常量PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化。如果动态地分配互斥量(例如通过调用malloc函数),那么在释放内存前需要调用pthread_mutex_destroy。
3.1创建及销毁互斥锁
函数原型
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
//返回值:若成功返回0,否则返回错误编号
//要用默认的属性初始化互斥量,只需把attr设置为NULL。
加锁及解锁
函数原型:
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
//返回值:若成功返回0,否则返回错误编号
代码如下:
#include <stdio.h>
#include <pthread.h>
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//void *(*start_routine) (void *), void *arg);
pthread_mutex_t mutex;
void *func1(void *arg){
int i ;
pthread_mutex_lock(&mutex);
for( i = 0 ; i<4 ; i++){
printf("t1 : thread ID is : %ld\n ",pthread_self());//打印线程的id
printf("t1 : pramm = %d \n", *((int *)arg));
sleep(1);
}
// void pthread_exit(void *retval);
pthread_mutex_unlock(&mutex);
}
void *func2(void *arg){
pthread_mutex_lock(&mutex);
printf("t2 : thread ID is : %ld\n ",pthread_self());//打印线程的id
printf("t2 : pramm = %d \n", *((int *)arg));
// void pthread_exit(void *retval);
pthread_mutex_unlock(&mutex);
}
int main(){
pthread_t t1;
pthread_t t2;
int pramm=100;
pthread_mutex_init(&mutex,NULL);
int ret= pthread_create(&t1, NULL ,func1 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret == 0 ){
// printf("thread1 success\n");
}
int ret2= pthread_create(&t2, NULL ,func2 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret2 == 0 ){
// printf("thread2 success\n");
}
printf("main : %ld\n",pthread_self());
// while(1);
// int pthread_join(pthread_t thread, void **retval);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
// printf("main : str = %s \n",*str);
pthread_mutex_destroy(&mutex);
return 0 ;
}
4.条件变量相关API
条件变量是线程另一可用的同步机制。条件变量给多个线程提供了一个会合的场所。条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。
条件本身是由互斥量保护的。线程在改变条件状态前必须首先锁住互斥量,其他线程在获得互斥量之前不会察觉到这种改变,因为必须锁定互斥量以后才能计算条件。
条件变量使用之前必须首先初始化,pthread_cond_t数据类型代表的条件变量可以用两种方式进行初始化,可以把常量PTHREAD_COND_INITIALIZER赋给静态分配的条件变量,但是如果条件变量是动态分配的,则需要使用pthread_cond_init函数对它进行初始化。
在释放条件变量底层的内存空间之前,可以使用pthread_cond_destroy函数对条件变量进行反初始化( deinitialize)。
创建及销毁条件变量
函数原型:
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);
//返回值:若成功返回0,否则返回错误编号
//注:除非需要创建一个非默认属性的条件变量,否则pthread_cont_init函数的attr参数可以设置为NULL。
****等待****
函数原型:
```c
#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, cond struct timespec *restrict timeout);
//返回值:若成功返回0,否则返回错误编号
注:pthread_cond_wait等待条件变为真。如果在给定的时间内条件不能满足,那么会生成一个代表一个出错码的返回变量。传递给pthread_cond_wait的互斥量对条件进行保护,调用者把锁住的互斥量传给函数。函数把调用线程放到等待条件的线程列表上,然后对互斥量解锁,这两个操作都是原子操作。这样就关闭了条件检查和线程进入休眠状态等待条件改变这两个操作之间的时间通道,这样线程就不会错过条件的任何变化。pthread_cond_wait返回时,互斥量再次被锁住。
触发
函数原型:
#include <pthread.h>
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
//返回值:若成功返回0,否则返回错误编号
这两个函数可以用于通知线程条件已经满足。pthread_cond_signal函数将唤醒等待该条件的某个线程,而pthread_cond_broadcast函数将唤醒等待该条件的所有进程。
注意一定要在改变条件状态以后再给线程发信号。
代码示例:
```c
#include <stdio.h>
#include <pthread.h>
// int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//void *(*start_routine) (void *), void *arg);
int cnt=0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *func1(void *arg){
static int gcc_n=0;
// printf("t1 : thread ID is : %ld\n ",pthread_self());//打印线程的id
// printf("t1 : pramm = %d \n", *((int *)arg));
// void pthread_exit(void *retval);
while(1){
pthread_cond_wait(&cond ,&mutex);//第一个参数为条件变量的地址 第二个参数为保护条件所对应的互斥锁的互斥变量的地址
printf("t1 :========================\n");
printf("t1 : %d\n",cnt);
cnt=0;
if(gcc_n++ == 10){
exit(0);
}
sleep(1);
}
}
void *func2(void *arg){
while(1){
pthread_mutex_lock(&mutex);
printf("t2 : %d\n",cnt++);
if(cnt == 3){
pthread_cond_signal(&cond);//唤醒等待该条件的某个线程
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(){
pthread_t t1;
pthread_t t2;
int pramm=100;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond ,NULL);//创建条件变量 第一个参数为条件变量 第二个参数为属性,设置为默认属性的话为NULL
int ret= pthread_create(&t1, NULL ,func1 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret == 0 ){
// printf("thread1 success\n");
}
int ret2= pthread_create(&t2, NULL ,func2 ,(void *)&pramm);//参数规定是void*类型,因此需要进行强转
if(ret2 == 0 ){
printf("thread2 success\n");
}
// while(1){
// printf("main : %d\n",cnt++);
// sleep(1);
// }
// printf("main : %ld\n",pthread_self());
// while(1);
// int pthread_join(pthread_t thread, void **retval);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);//参数为条件变量
// printf("main : str = %s \n",*str);
return 0 ;
}