天天看点

linux线程1.线程概述(与进程的区别及线程的优势)2.使用线程的理由3. 线程创建等待及退出4. 线程共享内存空间的代码验证5.线程同步之互斥量加锁解锁6.互斥锁限制共享资源的访问7.什么情况造成死锁(面试)8.线程条件控制实现线程的同步

linux线程

  • 1.线程概述(与进程的区别及线程的优势)
  • 2.使用线程的理由
  • 3. 线程创建等待及退出
    • 3.1 概述
    • 3.2 线程创建
    • 3.3 线程退出
    • 3.4 线程等待
    • 3.5 线程脱离
    • 3.6 线程ID获取及比较
    • 3.7 编程实战
  • 4. 线程共享内存空间的代码验证
  • 5.线程同步之互斥量加锁解锁
    • 5.1 与互斥锁相关的API
      • 5.1.1 创建及销毁互斥锁
      • 5.1.2 加锁及解锁
  • 6.互斥锁限制共享资源的访问
  • 7.什么情况造成死锁(面试)
  • 8.线程条件控制实现线程的同步
    • 8.1 创建及销毁条件变量
    • 8.2 线程等待
    • 8.3 触发
    • 8.4 实战编程
    • 8.5扩展

1.线程概述(与进程的区别及线程的优势)

(1).典型的UNIX/Linux进程可以看成只有一个控制线程:一个进程在同一时刻只做一件事情。有了多个控制线程后,在程序设计时可以把进程设计成在同一时刻做不止一件事,每个线程各自处理独立的任务。  

(2).进程是程序执行时的一个实例,是担当分配系统资源(CPU时间、内存等)的基本单位。在面向线程设计的系统中,进程本身不是基本运行单位,而是线程的容器。程序本身只是指令、数据及其组织形式的描述,进程才是程序(那些指令和数据)的真正运行实例。

(3).线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。线程包含了表示进程内执行环境必须的信息,其中包括进程中表示线程的线程ID、一组寄存器值、栈、调度优先级和策略、信号屏蔽字、errno常量以及线程私有数据。进程的所有信息对该进程的所有线程都是共享的,包括可执行的程序文本、程序的全局内存和堆内存、栈以及文件描述符。在Unix和类Unix操作系统中线程也被称为轻量级进程,但轻量级进程更多指的是内核线程(kernel thread),而把用户线程(user thread)称为线程。

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

进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程没有单独的地址空间,一个线程死掉就等于整个进程死掉,所以多进程的程序要比多线程的程序健壮,但在进程切换时,耗费资源较大,效率要差一些。但对于一些要求同时进行并且又要共享某些变量的并发操作,只能用线程,不能用进程。

从函数调用上来说,进程创建使用fork()操作;线程创建使用clone()操作。

2.使用线程的理由

从上面我们知道了进程与线程的区别,其实这些区别也就是我们使用线程的理由。总的来说就是:进程有独立的地址空间,线程没有单独的地址空间(同一进程内的线程共享进程的地址空间)。

使用多线程的理由之一是和进程相比,它是一种非常"节俭"的多任务操作方式。我们知道,在Linux系统下,启动一个新的进程必须分配给它独立的地址空间,建立众多的数据表来维护它的代码段、堆栈段和数据段,这是一种"昂贵"的多任务工作方式。而运行于一个进程中的多个线程,它们彼此之间使用相同的地址空间,共享大部分数据,启动一个线程所花费的空间远远小于启动一个进程所花费的空间,而且,线程间彼此切换所需的时间也远远小于进程间切换所需要的时间。据统计,总的说来,一个进程的开销大约是一个线程开销的30倍左右,当然,在具体的系统上,这个数据可能会有较大的区别。

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

除了以上所说的优点外,不和进程比较,多线程程序作为一种多任务、并发的工作方式,当然有以下的优点:

  • 提高应用程序响应。这对图形界面的程序尤其有意义,当一个操作耗时很长时,整个系统都会等待这个操作,此时程序不会响应键盘、鼠标、菜单的操作,而使用多线程技术,将耗时长的操作(time consuming)置于一个新的线程,可以避免这种尴尬的情况。
  • 使多CPU系统更加有效。操作系统会保证当线程数不大于CPU数目时,不同的线程运行于不同的CPU上。
  • 改善程序结构。一个既长又复杂的进程可以考虑分为多个线程,成为几个独立或半独立的运行部分,这样的程序会利于理解和修改。

3. 线程创建等待及退出

3.1 概述

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

linux线程1.线程概述(与进程的区别及线程的优势)2.使用线程的理由3. 线程创建等待及退出4. 线程共享内存空间的代码验证5.线程同步之互斥量加锁解锁6.互斥锁限制共享资源的访问7.什么情况造成死锁(面试)8.线程条件控制实现线程的同步

3.2 线程创建

#include <pthread.h>
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
(1)创建的线程名字
(2)通常NULL
(3)线程执行的函数
(4)给该函数传参(void *型)
           

当pthread_create成功返回时,由tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于定制各种不同的线程属性,暂可以把它设置为NULL,以创建默认属性的线程。

新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg。如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg参数传入。

3.3 线程退出

单个线程可以通过以下三种方式退出,在不终止整个进程的情况下停止它的控制流:

1)线程只是从启动例程中返回,返回值是线程的退出码。

2)线程可以被同一进程中的其他线程取消。

3)线程调用pthread_exit:

#include <pthread.h>
int pthread_exit(void *rval_ptr);
           

rval_ptr是一个无类型指针,与传给启动例程的单个参数类似。进程中的其他线程可以通过调用pthread_join函数访问到这个指针。

3.4 线程等待

#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函数将等待指定的线程终止,但并不获得线程的终止状态。

3.5 线程脱离

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

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

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

3.6 线程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
           

3.7 编程实战

#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);
//int pthread_join(pthread_t thread, void **rval_ptr);
//int pthread_exit(void *rval_ptr);

void *func1(void *arg)
{
	static int ret = 10;//一定要有static
//	static char *p = "t1 is run out!";
	
	printf("t1:%ld thread is create!\n",(unsigned long)pthread_self());// pthread_self()返回:调用线程的ID
	printf("t1:param is %d\n",*((int *)arg));

	pthread_exit((void *)&ret);//线程退出
//	pthread_exit((void *)p);
}
int main()
{
	int ret;
	int param = 100;
	pthread_t t1;
	
	int *pret = NULL;
//	char *pret = NULL;

//(1)创建的线程名字(2)通常NULL(3)线程执行的函数(4)给该函数传参(void *型)
	ret = pthread_create(&t1,NULL,func1,(void *)&param);
	if(ret == 0){// 返回:若成功返回0,否则返回错误编号
		printf("main:create t1 success!\n");
}	
	printf("main:%ld\n",(unsigned long)pthread_self());// pthread_self()返回:调用线程的ID
	pthread_join(t1,(void **)&pret);//线程等待
	printf("main:t1 quit:%d\n",*pret);
//	printf("main:t1 quit:%s\n",pret);
	
	return 0;
}
           

运行结果:

main:creat t1 succcess!
main:140299220043584 
t1:140299211519744 thread is creat!
t1:param is 100
main:t1 quit:10
           

4. 线程共享内存空间的代码验证

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
//int pthread_join(pthread_t thread, void **rval_ptr);

int g_data = 0;

void *func1(void *arg)
{
        printf("t1:%ld thread is 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 is creat!\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 *)&param);
	if(ret == 0){
		printf("main:create t1 success!\n");
	}

	ret = pthread_create(&t2,NULL,func2,(void *)&param);
	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);
	}
	
	pthread_join(t1,NULL);
	pthread_join(t2,NULL);
	
	return 0;
}
           

运行结果:

main:create t1 succcess!
t1:140340044936960 thread is create!
t1:param is 100
t1:0
main:create t2 succcess!
main:140340053460800 
main:1
t2:140340036544256 thread is create!
t2:param is 100
t2:2
t1:3
t2:4
main:5
...
可见线程共享同一内存。
           

5.线程同步之互斥量加锁解锁

linux线程1.线程概述(与进程的区别及线程的优势)2.使用线程的理由3. 线程创建等待及退出4. 线程共享内存空间的代码验证5.线程同步之互斥量加锁解锁6.互斥锁限制共享资源的访问7.什么情况造成死锁(面试)8.线程条件控制实现线程的同步

5.1 与互斥锁相关的API

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

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

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

5.1.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。
           

5.1.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就会失败,不能锁住互斥量,而返回EBUSY。

上锁的作用,一旦进入代码,一定是该部分的内容在一起执行,不会分开!!!
           
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
//int pthread_join(pthread_t thread, void **rval_ptr);

pthread_mutex_t mutex;//定义锁

void *func1(void *arg)
{
//int pthread_mutex_lock(pthread_mutex_t *mutex);
        pthread_mutex_lock(&mutex);//上锁

        for(int i=0;i<5;i++){
                printf("t1:%ld thread is creat!\n",(unsigned long)pthread_self());
                printf("t1:param is %d\n",*((int *)arg));
        }
//int pthread_mutex_unlock(pthread_mutex_t *mutex);
        pthread_mutex_unlock(&mutex);//解锁
}

void *func2(void *arg)
{
        pthread_mutex_lock(&mutex);//上锁

        printf("t2:%ld thread is creat!\n",(unsigned long)pthread_self());
        printf("t2:param is %d\n",*((int *)arg));

        pthread_mutex_unlock(&mutex);//解锁

}
int main()
{
        int ret;
        int param = 100;
        pthread_t t1;
        pthread_t t2;
//int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
        pthread_mutex_init(&mutex,NULL);//创建锁

        ret = pthread_create(&t1,NULL,func1,(void *)&param);
        if(ret == 0){
                printf("main:creat t1 succcess!\n");
        }

        ret = pthread_create(&t2,NULL,func2,(void *)&param);
        if(ret == 0){
                printf("main:creat t2 succcess!\n");
        }
        printf("main:%ld \n",(unsigned long)pthread_self());

        pthread_join(t1,NULL);
        pthread_join(t2,NULL);

//int pthread_mutex_destroy(pthread_mutex_t mutex);
        pthread_mutex_destroy(&mutex);//销毁锁

        return 0;
}
           

运行结果:

main:creat t1 succcess!
t1:140118170097408 thread is creat!
t1:param is 100
t1:140118170097408 thread is creat!
t1:param is 100
t1:140118170097408 thread is creat!
t1:param is 100
t1:140118170097408 thread is creat!
t1:param is 100
t1:140118170097408 thread is creat!
t1:param is 100
main:creat t2 succcess!
main:140118178621248 
t2:140118161704704 thread is creat!
t2:param is 100
上锁的作用,一旦进入代码,一定是该部分的内容在一起执行,不会分开!!!
           

6.互斥锁限制共享资源的访问

1 #include <stdio.h>
  2 #include <pthread.h>
  3 #include <unistd.h>
  4 #include <stdlib.h>
  5 //int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *res    trict arg);
  6 //int pthread_join(pthread_t thread, void **rval_ptr);
  7 //int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
  8 
  9 int g_data = 0;
 10 
 11 pthread_mutex_t mutex;
 12 
 13 void *func1(void *arg)
 14 {
 15         printf("t1:%ld thread is creat!\n",(unsigned long)pthread_self());
 16         printf("t1:param is %d\n",*((int *)arg));
 17 
 18         pthread_mutex_lock(&mutex);//上锁
 19         while(1){
 20                 printf("t1:%d\n",g_data++);
 21                 sleep(1);
 22                 if(g_data == 3){
 23                         pthread_mutex_unlock(&mutex);//解锁
 24 
 25                         printf("t1 quit===============================\n");
 26                 	    pthread_exit(NULL);
 27                  //     exit(0);
 28                 }
 29         }
 30 }
 32 void *func2(void *arg)
 33 {
 34         printf("t2:%ld thread is creat!\n",(unsigned long)pthread_self());
 35         printf("t2:param is %d\n",*((int *)arg));
 36 
 37         while(1){
 38                 printf("t2:%d\n",g_data);
 39 
 40                 pthread_mutex_lock(&mutex);//上锁
 41                 g_data++;
 42                 pthread_mutex_unlock(&mutex);//解锁
 43 
 44                 sleep(1);
 45         }
 46 }
 48 int main()
 49 {
 50         int ret;
 51         int param = 100;
 52         pthread_t t1;
 53         pthread_t t2;
 54 
 55         pthread_mutex_init(&mutex,NULL);
 56 
 57         ret = pthread_create(&t1,NULL,func1,(void *)&param);
 58         if(ret == 0){
 59                 printf("main:creat t1 succcess!\n");
 60         }
 61 
 62         ret = pthread_create(&t2,NULL,func2,(void *)&param);
 63         if(ret == 0){
 64                 printf("main:creat t2 succcess!\n");
 65         }
 66 
 67         printf("main:%ld \n",(unsigned long)pthread_self());
 68 
 69         while(1){
 70                 printf("main:%d\n",g_data);
 71                 sleep(1);
 72         }
 73 
 74         pthread_join(t1,NULL);
 75         pthread_join(t2,NULL);
 76 
 77          pthread_mutex_destroy(&mutex);
 78 
 79         return 0;
 80 }
           

运行结果:

main:creat t1 succcess!
t1:140014486624000 thread is creat!
t1:param is 100
t1:0
main:creat t2 succcess!
main:140014495147840 
main:1
t2:140014478231296 thread is creat!
t2:param is 100
t2:1
t1:1
main:2
main:2
t1:2
main:3
t1 quit===============================
main:4
t2:4
main:5
t2:5
t2:6
main:6
main:7
t2:7
...(每次运行结果数据可能不同,但后面相同)
           
线程1和线程2不知谁先会运行,但是一旦进去线程1(func1)中,就会上锁,知道g_data=3时解锁,并且线程1结束,之后只有线程2和main在运行
若代码中26行注释 27取消注释,当线程1中的g_data到达3时,exit()函数生效,程序退出,
因为:线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。
           

7.什么情况造成死锁(面试)

当程序中有两把锁的时候,而且两者都想具有两把锁,当线程1手里握着一把锁,而线程2手里握着另一把锁,而且对方都想要对方手里的那把锁,谁都不肯让步的时候,就会造成死锁,这时候就会形成一个僵局,两个线程都会被阻塞而不能执行。

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
//int pthread_join(pthread_t thread, void **rval_ptr);

int g_data = 0;

pthread_mutex_t mutex;
pthread_mutex_t mutex2;


void *func1(void *arg)
{
//int pthread_mutex_lock(pthread_mutex_t mutex);
        pthread_mutex_lock(&mutex);//上锁1
        sleep(1);
        pthread_mutex_lock(&mutex2);//上锁2

        for(int i=0;i<5;i++){
                printf("t1:%ld thread is creat!\n",(unsigned long)pthread_self());
                printf("t1:param is %d\n",*((int *)arg));
                sleep(1);
        }
//int pthread_mutex_unlock(pthread_mutex_t mutex);
        pthread_mutex_unlock(&mutex);
}
void *func2(void *arg)
{
        pthread_mutex_lock(&mutex2);//上锁2
        sleep(1);
        pthread_mutex_lock(&mutex);//上锁1


        printf("t2:%ld thread is 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);//上锁1

        printf("t3:%ld thread is 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;

//int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
        pthread_mutex_init(&mutex,NULL);
        pthread_mutex_init(&mutex2,NULL);

        ret = pthread_create(&t1,NULL,func1,(void *)&param);
        if(ret == 0){
                printf("main:creat t1 succcess!\n");
        }

        ret = pthread_create(&t2,NULL,func2,(void *)&param);
        if(ret == 0){
                printf("main:creat t2 succcess!\n");
        }

        ret = pthread_create(&t3,NULL,func3,(void *)&param);
        if(ret == 0){
                printf("main:creat t3 succcess!\n");
        }

        printf("main:%ld \n",(unsigned long)pthread_self());


        pthread_join(t1,NULL);
        pthread_join(t2,NULL);
        pthread_join(t3,NULL);

//int pthread_mutex_destroy(pthread_mutex_t mutex);
        pthread_mutex_destroy(&mutex);
        pthread_mutex_destroy(&mutex2);

        return 0;
}
           

运行结果

main:creat t1 succcess!
main:creat t2 succcess!
main:creat t3 succcess!
main:139997967955776 
程序卡死在这里
           
线程是同时运行的,若先进入线程1则上锁2,睡眠1s,给线程2足够的时间,线程2上锁1,但此时线程1继续运行时需要上锁1,但该锁已经被线程2获取,同时线程2继续运行时需要上锁2,该锁被线程1获取,两者停滞不前,卡死在这。
           

8.线程条件控制实现线程的同步

linux线程1.线程概述(与进程的区别及线程的优势)2.使用线程的理由3. 线程创建等待及退出4. 线程共享内存空间的代码验证5.线程同步之互斥量加锁解锁6.互斥锁限制共享资源的访问7.什么情况造成死锁(面试)8.线程条件控制实现线程的同步

8.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。

8.2 线程等待

#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结构指定。

8.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函数将唤醒等待该条件的所有进程。

注意一定要在改变条件状态以后再给线程发信号

8.4 实战编程

1 #include <stdio.h>
  2 #include <pthread.h>
  3 #include <unistd.h>
  4 #include <stdlib.h>
  5 //int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *res    trict arg);
  6 //int pthread_join(pthread_t thread, void **rval_ptr);
  7 //int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
  8 
  9 int g_data = 0;
 10 
 11 
 12 //pthread_mutex_t mutex ;
 13 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//静态初始化
 14 //pthread_cond_t cond ;//dongtaichushihua
 15 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
 16 
 17 void *func1(void *arg)
 18 {
 19         printf("t1:%ld thread is creat!\n",(unsigned long)pthread_self());
 20         printf("t1:param is %d\n",*((int *)arg));
 21 
 22         static int cnt =0;
 23 
 24         while(1){
 25 
 26                 pthread_cond_wait(&cond,&mutex);//等待条件发生
 27 
 28                 printf("t1 run===============================\n");
 29 
 30                 printf("t1:%d\n",g_data);
 31                 g_data =0;
 32                 sleep(1);
 33                 if(cnt++ == 10){
 34                         exit(1);
 35                 }
 36         }
 37 }
 38 
 39 void *func2(void *arg)
 40 {
 41         printf("t2:%ld thread is creat!\n",(unsigned long)pthread_self());
 42         printf("t2:param is %d\n",*((int *)arg));
 43 
 44         while(1){
 45                 printf("t2:%d\n",g_data);
 46 
 47                 pthread_mutex_lock(&mutex);//shang suo
 48                 g_data++;
 49                 if(g_data == 3){
 50                         pthread_cond_signal(&cond);//触发 触发之后func1运行 
 51                 }
 52                 pthread_mutex_unlock(&mutex);//jie suo
 53                 sleep(1);
 54         }
 55 }
 56 
 57 int main()
 58 {
 59         int ret;
 60         int param = 100;
 61         pthread_t t1;
 62         pthread_t t2;
 63 
 64 //      pthread_mutex_init(&mutex,NULL);
 65 //      pthread_cond_init(&cond,NULL);
 66 
 67         ret = pthread_create(&t1,NULL,func1,(void *)&param);
 68         if(ret == 0){
 69 //              printf("main:creat t1 succcess!\n");
 70         }
 71 
 72         ret = pthread_create(&t2,NULL,func2,(void *)&param);
 73         if(ret == 0){
 74 //              printf("main:creat t2 succcess!\n");
 75         }
 76 
 77 //      printf("main:%ld \n",(unsigned long)pthread_self());
 78 
 79 
 80         pthread_join(t1,NULL);
 81         pthread_join(t2,NULL);
 82 
 83          pthread_mutex_destroy(&mutex);
 84          pthread_cond_destroy(&cond);
 85 
 86         return 0;
 87 }
           

运行结果

t1:140348760086272 thread is creat!
t1:param is 100
t2:140348751693568 thread is creat!
t2:param is 100
t2:0
t2:1
t2:2
t1 run===============================
t1:3
t2:0
t2:1
t2:2
t1 run===============================
t1:3
t2:0
t2:1
t2:2
t1 run===============================
t1:3
t2:0
t2:1
t2:2
t1 run===============================
...
           
13和15行的初始化为静态初始化,而12、14和64、65行为动态初始化
           

8.5扩展

可把运行的结果存放到文件中,在后台运行,不在软件页面内运行

int main(int argc,char **argv)
{

        int time = atoi(argv[1]);
        for(int i=0;i<time;i++){
                system("./demo8");
        }

}


./a.out 10 >>text.ret.txt &
到text.ret.txt文件中查看运行结果。
           

继续阅读