原文出自https://www.cnblogs.com/xiehongfeng100/p/4620852.html
Linux线程的简单介绍
进程是程序执行时的一个实例,是担当分配系统资源(CPU时间、内存等)的基本单位。在面向线程设计的系统中,进程本身不是基本运行单位,而是线程的容器。程序本身只是指令、数据及其组织形式的描述,进程才是程序(那些指令和数据)的真正运行实例。
进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程没有单独的地址空间,一个线程死掉就等于整个进程死掉,所以多进程的程序要比多线程的程序健壮,但在进程切换时,耗费资源较大,效率要差一些。但对于一些要求同时进行并且又要共享某些变量的并发操作,只能用线程,不能用进程。
“进程——资源分配的最小单位,线程——程序执行的最小单位”
使用线程的理由
理由一:它是一种非常"节俭"的多任务操作方式。我们知道,在Linux系统下,启动一个新的进程必须分配给它独立的地址空间,建立众多的数据表来维护它的代码段、堆栈段和数据段,这是一种"昂贵"的多任务工作方式。而运行于一个进程中的多个线程,它们彼此之间使用相同的地址空间,共享大部分数据,启动一个线程所花费的空间远远小于启动一个进程所花费的空间,而且,线程间彼此切换所需的时间也远远小于进程间切换所需要的时间。据统计,总的说来,一个进程的开销大约是一个线程开销的30倍左右,当然,在具体的系统上,这个数据可能会有较大的区别。
理由二:使用多线程的理由之二是线程间方便的通信机制。对不同进程来说,它们具有独立的数据空间,要进行数据的传递只能通过通信的方式进行,这种方式不仅费时,而且很不方便。线程则不然,由于同一进程下的线程之间共享数据空间,所以一个线程的数据可以直接为其它线程所用,这不仅快捷,而且方便。当然,数据的共享也带来其他一些问题,有的变量不能同时被两个线程所修改,有的子程序中声明为static的数据更有可能给多线程程序带来灾难性的打击,这些正是编写多线程程序时最需要注意的地方。
Linux上线程开发API概要多线程开发在 Linux 平台上已经有成熟的 pthread 库支持。其涉及的多线程开发的最基本概念主要包含三点:线程,互斥锁,条件。其中,线程操作又分线程的创建,退出,等待 3 种。互斥锁则包括 4 种操作,分别是创建,销毁,加锁和解锁。条件操作有 5 种操作:创建,销毁,触发,广播和等待。其他的一些线程扩展概念,如信号灯等,都可以通过上面的三个基本元素的基本操作封装出来。详细请见下表:
一、线程的创建、退出、等待
- 线程创建
#include <pthread.h>
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
当pthread_create成功返回时,由tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于定制各种不同的线程属性,暂可以把它设置为NULL,以创建默认属性的线程。
新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg。如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg参数传入。
2.线程退出
单个线程可以通过以下三种方式退出,在不终止整个进程的情况下停止它的控制流:
1)线程只是从启动例程中返回,返回值是线程的退出码。
2)线程可以被同一进程中的其他线程取消。
3)线程调用pthread_exit:
#include <pthread.h>
int pthread_exit(void *rval_ptr);
rval_ptr是一个无类型指针,与传给启动例程的单个参数类似。进程中的其他线程可以通过调用pthread_join函数访问到这个指针。
3.线程等待
#include <pthread.h>
int pthread_join(pthread_t thread, void **rval_ptr);
// 返回:若成功返回0,否则返回错误编号
如果对线程的返回值不感兴趣,可以把rval_ptr置为NULL。在这种情况下,调用pthread_join函数将等待指定的线程终止,但并不获得线程的终止状态。
4.线程ID获取及比较
#include <pthread.h>
pthread_t pthread_self(void);
// 返回:调用线程的ID
对于线程ID比较,为了可移植操作,我们不能简单地把线程ID当作整数来处理,因为不同系统对线程ID的定义可能不一样。我们应该要用下边的函数:
#include <pthread.h>
int pthread_equal(pthread_t tid1, pthread_t tid2);
// 返回:若相等则返回非0值,否则返回0
实例
#include <stdio.h>
#include <pthread.h>
/* int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
*/
//pthread_t pthread_self(void);
// 返回:调用线程的ID
//int pthread_exit(void *rval_ptr);
//int pthread_join(pthread_t thread, void **rval_ptr);
// 返回:若成功返回0,否则返回错误编号
void *func1(void *arg)
{
static char *p = "t1 is run out";
printf("ti: %ld thread is create\n",(unsigned long)pthread_self());
printf("t1: param is %d\n",*((int *)arg));
pthread_exit((void *)p);
}
int main()
{
int ret;
int param = 100;
char *pret=NULL;
pthread_t t1;
ret = pthread_create(&t1,NULL,func1,(void *)¶m);
if(ret==0){
printf("main: create t1 success\n");
}
printf("main: %ld\n",(unsigned long)pthread_self());
// while(1);
pthread_join(t1,(void **)&pret);//此处注意加上&符号
printf("main: t1 quit: %s\n",pret);
return 0;
}
线程共享内存空间的代码验证
#include <stdio.h>
#include <pthread.h>
/* int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
*/
//pthread_t pthread_self(void);
// 返回:调用线程的ID
int g_data = 0;
void *func1(void *arg)
{
printf("t1: %ld thread is create\n",(unsigned long)pthread_self());
printf("t1: param is %d\n",*((int *)arg));
while(1){
printf("t1:%d\n",g_data++);
sleep(1);
if(g_data==3){
pthread_exit(NULL);
}
}
}
void *func2(void *arg)
{
printf("t2: %ld thread is create\n",(unsigned long)pthread_self());
printf("t2: param is %d\n",*((int *)arg));
while(1){
printf("t2:%d\n",g_data++);
sleep(1);
}
}
int main()
{
int ret;
int param = 100;
pthread_t t1;
pthread_t t2;
ret = pthread_create(&t1,NULL,func1,(void *)¶m);
if(ret==0){
printf("main: create t1 success\n");
}
ret = pthread_create(&t2,NULL,func2,(void *)¶m);
if(ret==0){
printf("main: create t2 success\n");
}
printf("main: %ld\n",(unsigned long)pthread_self());
while(1){
printf("main: %d\n",g_data++);
sleep(1);
}
// while(1);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
return 0;
}
二、互斥锁创建、销毁、加锁、解锁
互斥量就是一把锁!!!!
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。
2.加锁及解锁
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t mutex);
int pthread_mutex_trylock(pthread_mutex_t mutex);//自行查询相关资料
int pthread_mutex_unlock(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号
实例
#include <stdio.h>
#include <pthread.h>
/* int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
*/
//pthread_t pthread_self(void);
// 返回:调用线程的ID
int g_data = 0;
pthread_mutex_t mutex;
void *func1(void *arg)
{
printf("t1: %ld thread is create\n",(unsigned long)pthread_self());
printf("t1: param is %d\n",*((int *)arg));
pthread_mutex_lock(&mutex);
while(1){
printf("t1:%d\n",g_data++);
sleep(1);
if(g_data==3){
pthread_mutex_unlock(&mutex);
printf("ti quit===============================\n");
// pthread_exit(NULL);
exit(0);
}
}
}
void *func2(void *arg)
{
printf("t2: %ld thread is create\n",(unsigned long)pthread_self());
printf("t2: param is %d\n",*((int *)arg));
while(1){
printf("t2:%d\n",g_data);
pthread_mutex_lock(&mutex);
g_data++;
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
int ret;
int param = 100;
pthread_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);//动态初始化锁!!!!!!
ret = pthread_create(&t1,NULL,func1,(void *)¶m);
if(ret==0){
printf("main: create t1 success\n");
}
ret = pthread_create(&t2,NULL,func2,(void *)¶m);
if(ret==0){
printf("main: create t2 success\n");
}
printf("main: %ld\n",(unsigned long)pthread_self());
while(1){
printf("main: %d\n",g_data);
sleep(1);
}
// while(1);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
3.什么情况下会造成死锁
#include <stdio.h>
#include <pthread.h>
/* int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
*/
//pthread_t pthread_self(void);
// 返回:调用线程的ID
int g_data = 0;
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
void *func1(void *arg)
{
int i;
pthread_mutex_lock(&mutex);
sleep(1);
pthread_mutex_lock(&mutex2);
for(i=0;i<5;i++){
printf("t1: %ld thread is create\n",(unsigned long)pthread_self());
printf("t1: param is %d\n",*((int *)arg));
sleep(1);
}
pthread_mutex_unlock(&mutex);
}
void *func2(void *arg)
{
pthread_mutex_lock(&mutex2);
sleep(1);
pthread_mutex_lock(&mutex);
printf("t2: %ld thread is create\n",(unsigned long)pthread_self());
printf("t2: param is %d\n",*((int *)arg));
pthread_mutex_unlock(&mutex);
}
void *func3(void *arg)
{
pthread_mutex_lock(&mutex);
printf("t3: %ld thread is create\n",(unsigned long)pthread_self());
printf("t3: param is %d\n",*((int *)arg));
pthread_mutex_unlock(&mutex);
}
int main()
{
int ret;
int param = 100;
pthread_t t1;
pthread_t t2;
pthread_t t3;
pthread_mutex_init(&mutex,NULL);
pthread_mutex_init(&mutex2,NULL);
ret = pthread_create(&t1,NULL,func1,(void *)¶m);
if(ret==0){
printf("main: create t1 success\n");
}
ret = pthread_create(&t2,NULL,func2,(void *)¶m);
if(ret==0){
printf("main: create t2 success\n");
}
ret = pthread_create(&t3,NULL,func3,(void *)¶m);
if(ret==0){
printf("main: create t3 success\n");
}
printf("main: %ld\n",(unsigned long)pthread_self());
// while(1);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&mutex2);
return 0;
}
三、条件变量
条件变量是线程另一可用的同步机制。条件变量给多个线程提供了一个会合的场所。条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。
条件本身是由互斥量保护的。线程在改变条件状态前必须首先锁住互斥量,其他线程在获得互斥量之前不会察觉到这种改变,因为必须锁定互斥量以后才能计算条件。
条件变量使用之前必须首先初始化,pthread_cond_t数据类型代表的条件变量可以用两种方式进行初始化,可以把常量PTHREAD_COND_INITIALIZER赋给静态分配的条件变量,但是如果条件变量是动态分配的,可以使用pthread_cond_destroy函数对条件变量进行去除初始化(deinitialize)。
1.创建及销毁条件变量
#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。
- 等待
#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返回时,互斥量再次被锁住。
pthread_cond_timedwait函数的工作方式与pthread_cond_wait函数类似,只是多了一个timeout。timeout指定了等待的时间,它是通过timespec结构指定。
3. 触发
#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函数将唤醒等待该条件的所有进程。
注意一定要在改变条件状态以后再给线程发信号。
实例
#include <stdio.h>
#include <pthread.h>
/* int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
*/
//pthread_t pthread_self(void);
// 返回:调用线程的ID
int g_data = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *func1(void *arg)
{
printf("t1: %ld thread is create\n",(unsigned long)pthread_self());
printf("t1: param is %d\n",*((int *)arg));
static int cnt = 0;
while(1){
pthread_cond_wait(&cond,&mutex);
printf("ti run ===============================\n");
printf("t1: %d\n",g_data);
g_data=0;
sleep(1);
printf(" text\n ");//此处出现了线程func1和func2之间的竞争,消除竞争只需把上一语句去掉
if(cnt++==3){
exit(1);
}
}
}
void *func2(void *arg)
{
printf("t2: %ld thread is create\n",(unsigned long)pthread_self());
printf("t2: param is %d\n",*((int *)arg));
while(1){
printf("t2:%d\n",g_data);
pthread_mutex_lock(&mutex);
g_data++;
if(g_data==3){
pthread_cond_signal(&cond);//满足条件状态给线程发信号
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
int ret;
int param = 100;
pthread_t t1;
pthread_t t2;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
ret = pthread_create(&t1,NULL,func1,(void *)¶m);
if(ret==0){
// printf("main: create t1 success\n");
}
ret = pthread_create(&t2,NULL,func2,(void *)¶m);
if(ret==0){
// printf("main: create t2 success\n");
}
// printf("main: %ld\n",(unsigned long)pthread_self());
// while(1);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
4.静态初始化(利用宏)
#include <stdio.h>
#include <pthread.h>
/* int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
*/
//pthread_t pthread_self(void);
// 返回:调用线程的ID
int g_data = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *func1(void *arg)
{
printf("t1: %ld thread is create\n",(unsigned long)pthread_self());
printf("t1: param is %d\n",*((int *)arg));
static int cnt = 0;
while(1){
pthread_cond_wait(&cond,&mutex);
printf("ti run ===============================\n");
printf("t1: %d\n",g_data);
g_data=0;
sleep(1);
if(cnt++==3){
exit(1);
}
}
}
void *func2(void *arg)
{
printf("t2: %ld thread is create\n",(unsigned long)pthread_self());
printf("t2: param is %d\n",*((int *)arg));
while(1){
printf("t2:%d\n",g_data);
pthread_mutex_lock(&mutex);
g_data++;
if(g_data==3){
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
int ret;
int param = 100;
pthread_t t1;
pthread_t t2;
// pthread_mutex_init(&mutex,NULL);
// pthread_cond_init(&cond,NULL);
ret = pthread_create(&t1,NULL,func1,(void *)¶m);
if(ret==0){
// printf("main: create t1 success\n");
}
ret = pthread_create(&t2,NULL,func2,(void *)¶m);
if(ret==0){
// printf("main: create t2 success\n");
}
// printf("main: %ld\n",(unsigned long)pthread_self());
// while(1);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}