线程(thread)

线程介绍

进程与线程

        典型的Linux进程可以看作只有一个控制线程:一个进程在同一时刻只能做一件事情。有了多个控制线程,就可以把程序设计成同一时刻做不止一件事情,每个线程都有各自要处理的任务。

        进程是程序执行的一个实例。它是担当分配系统资源,如CPU时间、内存等的基本单位。在面向线程设计的系统中,进程本身不是运行的基本单位,而是线程的容器。

程序本身只是指令数据以及数据形式的描述进程是程序(指令数据)的真正运行实例

        线程是操作系统中能够进行运算调度的最小单位。一条线程指的是进程中一个单一顺序的控制流,一个进程可以并发多个线程,每条线程并执行不同的任务。线程包含了表示进程内执行环境必须的信息,其中包括了进程中表示线程的线程ID,一组数据寄存器站调度,优先级和策略信号屏蔽字、errno常量以及线程私有数据。进程的所有信息对该进程的所有线程都是共享的,包括可执行的程序文本程序的全局内存和堆内存栈以及文件描述符。

        进程是资源分配最小的单位,线程是程序执行的最小单位。

        进程有独立的地址空间,一个进程崩溃之后,在保护模式下不会对其他进程产生影响。而线程只是一个进程中的不同执行路径,线程有自己的堆栈和局部变量,但线程没有单独的地址空间一个线程死掉就等于整个进程死掉,所以多进程的程序要比多线程的程序健壮。但在进程切换的过程损耗内存较大,效率要差一点。

使用线程的理由

        进程与线程的区别:总的来说就是进程有独立的地址空间,线程没有单独的地址空间(同一进程内的线程共享进程的地址空间)

        使用多线程的理由之一:与进程相比,它是一种非常节俭的多任务操作方式。在Linux系统下启动一个新进程,必须分配给他独立的地址空间,建立众多的数据表来维护它的代码段、堆栈段和数据段,这是一种昂贵的多任务方式。而运行于一个进程中的多个线程,他们彼此之间使用相同的地址空间共享大部分的数据,启动一个线程所花费的空间远远小于启动一个进程所花费的空间,县城监别,以此切换的时间已远远小于进程间切换的时间。

        使用多线程的理由之二:线程间方便的通信机制。对于不同的进程来说,他们具有独立的数据空间,要进行数据的传递,只能通过通信的方式,这种方式不仅费时,而且很不方便。线程由于在同一进程下线程之间共享数据空间,所以一个线程的数据可以直接为其他线程所用,这不仅快捷而且方便。由于数据的共享也会带来一些问题,有的变量不能同时被两个线程所修改。有的子进程中声明了static的数据更有可能给多线程带来灾难性的打击。

线程开发API概要

        多线程开发在 Linux 平台上已经有成熟的 pthread 库支持。其涉及的多线程开发的最基本概念主要包含三点:线程,互斥锁,条件。其中,线程操作又分线程的创建,退出,等待 3 种。互斥锁则包括 4 种操作,分别是创建,销毁,加锁和解锁。条件操作有 5 种操作:创建,销毁,触发,广播和等待。其他的一些线程扩展概念,如信号灯等,都可以通过上面的三个基本元素的基本操作封装出来。详细请见下表:

3a47cd5335f45570821484258951d65e.png

 与线程自身相关API

        1. 线程创建

#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,否则返回错误编号

  调用这个函数的线程将一直阻塞,直到指定的线程调用pthread_exit、从启动例程中返回或者被取消。如果例程只是从它的启动例程返回i,rval_ptr将包含返回码。如果线程被取消,由rval_ptr指定的内存单元就置为PTHREAD_CANCELED。

  可以通过调用pthread_join自动把线程置于分离状态,这样资源就可以恢复。如果线程已经处于分离状态,pthread_join调用就会失败,返回EINVAL。

  如果对线程的返回值不感兴趣,可以把rval_ptr置为NULL。在这种情况下,调用pthread_join函数将等待指定的线程终止,但并不获得线程的终止状态

  4. 线程脱离

  一个线程或者是可汇合(joinable,默认值),或者是脱离的(detached)。当一个可汇合的线程终止时,它的线程ID和退出状态将留存到另一个线程对它调用pthread_join。脱离的线程却像守护进程,当它们终止时,所有相关的资源都被释放,我们不能等待它们终止。如果一个线程需要知道另一线程什么时候终止,那就最好保持第二个线程的可汇合状态。

  pthread_detach函数把指定的线程转变为脱离状态。

#include <pthread.h>
int pthread_detach(pthread_t thread);
// 返回:若成功返回0,否则返回错误编号

  本函数通常由想让自己脱离的线程使用,就如以下语句:

pthread_detach(pthread_self());

  5. 线程ID获取及比较

#include <pthread.h>
pthread_t pthread_self(void);
// 返回:调用线程的ID

  对于线程ID比较,为了可移植操作,我们不能简单地把线程ID当作整数来处理,因为不同系统对线程ID的定义可能不一样。我们应该要用下边的函数:

#include <pthread.h>
pthread_t pthread_self(void);
// 返回:调用线程的ID

  对于多线程程序来说,我们往往需要对这些多线程进行同步。同步(synchronization)是指在一定的时间内只允许某一个线程访问某个资源。而在此时间内,不允许其它的线程访问该资源。我们可以通过互斥锁(mutex),条件变量(condition variable)和读写锁(reader-writer lock)来同步资源。

        线程的使用demo如下:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, 
//						void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号

//int pthread_exit(void *rval_ptr);

//int pthread_join(pthread_t thread, void **rval_ptr);

void *func1(void *arg)
{
	static int ret = 10;//必须用static定义,在线程结束以后也会将ret = 10保存下来

	//打印线程pid	pthread_t self()
	printf("t1:%ld thread in creat pid\n",(unsigned long)pthread_self() );
	//打印main函数传递的arg参数
	printf("t1:arg = %d\n",*((int *)arg));

	//线程退出	退出保存ret的值
	pthread_exit((void *)&ret);
}


int main()
{
	int ret;
	pthread_t t1;
	int arg = 100;

	int *pret = NULL;//定义一个指针,在这里写不写NULL都对,下面的(void **)&pret会将指针重新指向func1
//	char *pret = NULL;
	//线程创建  新创建的线程从func1函数的地址开始运行,该函数只有一个无类型指针参数arg
	ret = pthread_create(&t1,NULL,func1,(void *)&arg);
						//线程地址,线程属性默认为NULL

	if( ret == 0 ){
		printf("main thread pid:%ld \n",(unsigned long)pthread_self());

		//线程等待、阻塞 使线程t1得以运行
		pthread_t join(t1,(void **)&pret );
		printf("main:t1 quit:%d\n",*pret);
	}

	return 0;
}
main thread pid:140388533372672 
t1:140388525086464 thread in creat pid
t1:arg = 100
main:t1 quit:10

        如何体现多个线程共用一个地址空间(多个进程对同一个数据进行修改)

#include <stdio.h>
#include <pthread.h>

int g_data = 0;	//线程共用一个内存,对g_data进行操作

void *func1(void *arg)
{
        printf("t1:%ld thread in creat\n",(unsigned long)pthread_self());
        printf("t1:param is:%d\n",*((int *)arg));
        while(1){
                printf("t1: %d\n",g_data++);
                sleep(1);
        }
}
void *func2(void *arg)
{
        printf("t2:%ld thread in creat\n",(unsigned long)pthread_self());
        printf("t2:param is:%d\n",*((int *)arg));
        while(1){
                printf("t2: %d\n",g_data++);
                sleep(1);	//睡眠1秒
        }
}
int main()
{
        int ret;
        int param=100;
        pthread_t t1;
        pthread_t t2;
        
        ret = pthread_create(&t1,NULL, func1, (void *)&param);
        if(ret == 0){
                printf("creat t1 success\n");
        }
        ret = pthread_create(&t2,NULL, func2, (void *)&param);
        if(ret == 0){
                printf("creat t2 success\n");
        }

        printf("main:%ld\n",(unsigned long)pthread_self());
        while(1){
                printf("main: %d\n",g_data++);
                sleep(1);
        }
        pthread_join(t1,NULL);
        pthread_join(t2,NULL);
        return 0;
}
CLC@Embed_Learn:~/THREAD$ ./a.out 
creat t1 success
t1:140448948406016 thread in creat
t1:param is:100
t1: 0
creat t2 success
main:140448956692224
main: 1
t2:140448940013312 thread in creat
t2:param is:100
t2: 2
t1: 3
main: 4
t2: 5
t1: 6
main: 7
t2: 8
t1: 9
main: 10
t2: 11    //main t1 t2 三个线程轮流对data++

互斥锁

        互斥量(mutex)从本质上来说是一把,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。对互斥量进行加锁后,任何其他试图再次对互斥量加锁的线程将会被阻塞直到当前线程释放该互斥锁。如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上的阻塞线程都会变成可运行状态,第一个变为可运行状态的线程可以对互斥量加锁,其他线程将会看到互斥锁依然被锁住,只能回去等待它重新变为可用。在这种方式下,每次只有一个线程可以向前运行。

        在设计时需要规定所有的线程必须遵守相同的数据访问规则。只有这样,互斥机制才能正常工作。操作系统并不会做数据访问的串行化。如果允许其中的某个线程在没有得到锁的情况下也可以访问共享资源,那么即使其它的线程在使用共享资源前都获取了锁,也还是会出现数据不一致的问题。

        互斥变量用pthread_mutex_t数据类型表示。在使用互斥变量前必须对它进行初始化,可以把它置为常量PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化。如果动态地分配互斥量(例如通过调用malloc函数),那么在释放内存前需要调用pthread_mutex_destroy。

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,否则返回错误编号

        如果线程不希望被阻塞,它可以使用pthread_mutex_trylock尝试对互斥量进行加锁。如果调用pthread_mutex_trylock时互斥量处于未锁住状态,那么pthread_mutex_trylock将锁住互斥量,不会出现阻塞并返回0,否则pthread_mutex_trylock就会失败,不能锁住互斥锁

#include <stdio.h>
#include <pthread.h>

int g_data = 0;

pthread_mutex_t mutex;//锁

void *func1(void *arg)
{
        int i;
        pthread_mutex_lock(&mutex);	//加锁
        for(i=0;i<5;i++){
                printf("t1:%ld thread in creat\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(&mutex);	//加锁
        printf("t2:%ld thread in creat\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 in creat\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);//创建锁

        ret = pthread_create(&t1,NULL, func1, (void *)&param);	//创建线程t1
        if(ret == 0){
                printf("creat t1 success\n");
        }
        ret = pthread_create(&t2,NULL, func2, (void *)&param);	//创建线程t2
        if(ret == 0){
                printf("creat t2 success\n");
        }
        ret = pthread_create(&t3,NULL, func3, (void *)&param);	//创建线程t3
        if(ret == 0){
                printf("creat t3 success\n");
        }

        printf("main:%ld\n",(unsigned long)pthread_self());//获取线程ID

        pthread_join(t1,NULL);	//等待
        pthread_join(t2,NULL);	//等待
        pthread_join(t3,NULL);	//等待
        return 0;
}


CLC@Embed_Learn:~/THREAD$ gcc pthread6.c -lpthread
CLC@Embed_Learn:~/THREAD$ ./a.out 
creat t1 success
creat t2 success
t1:140408382326528 thread in creat
t1:param is:100
creat t3 success
main:140408390612736
t1:140408382326528 thread in creat
t1:param is:100
t1:140408382326528 thread in creat
t1:param is:100
t1:140408382326528 thread in creat
t1:param is:100
t1:140408382326528 thread in creat
t1:param is:100
t3:140408365541120 thread in creat
t3:param is:100
t2:140408373933824 thread in creat
t2:param is:100
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

int g_data = 0;
pthread_mutex_t mutex;	//定义锁
void *func1(void *arg)
{
        printf("t1:%ld thread in creat\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){	//定义在g_data等于3的时候退出程序
                        pthread_mutex_unlock(&mutex);//解锁
                //      pthread_exit(NULL);
                        printf("quit==================================\n");
                        exit(0);
                }
        }

}


void *func2(void *arg)
{
        printf("t2:%ld thread in creat\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);	//加锁,func2函数在加锁之后才能对g_data操作
                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 *)&param);
        if(ret == 0){
                printf("creat t1 success\n");
        }
        ret = pthread_create(&t2,NULL, func2, (void *)&param);
        if(ret == 0){
                printf("creat t2 success\n");
        }

        printf("main:%ld\n",(unsigned long)pthread_self());
        while(1){
                printf("main: %d\n",g_data);
                sleep(1);
        }
        pthread_join(t1,NULL);
        pthread_join(t2,NULL);
        pthread_mutex_destroy(&mutex);	//销毁锁

        return 0;
}

creat t1 success
creat t2 success
main:139756576401152
main: 0
t2:139756559722240 thread in creat
t2:param is:100
t2: 0
t1:139756568114944 thread in creat
t1:param is:100
t1: 1
main: 2
t2: 2
t1: 2
main: 3
quit==================================

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值