Linux系统编程之线程(多线程编程初探)

在讲线程之前,我们先来看看线程与进程之间的关系:
以下两部分来自优秀博文:Linux多线程编程初探优秀博文
进程与线程:
典型的UNIX/linux进程可以看成是只有一个控制线程,一个进程在同一时刻只做一件事情,有了多个控制线程后,在程序设计时可以把进程设计成在同一时刻做不止一件事,每个线程各自处理独立的任务。
进程是程序执行时的一个实例,是担当分配系统资源(CPU时间、内存等)的基本单位。在面向线程设计的系统中,进程本身不是基本运行单位,而是线程的容器。程序本身只是指令、数据及其组织形式的描述,进程才是程序(那些指令和数据)的真正运行实例。
线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。线程包含了表示进程内执行环境必须的信息,其中包括进程中表示线程的线程ID、一组寄存器值、栈、调度优先级和策略、信号屏蔽字、errno常量以及线程私有数据。进程的所有信息对该进程的所有线程都是共享的,包括可执行的程序文本、程序的全局内存和堆内存、栈以及文件描述符。在Unix和类Unix操作系统中线程也被称为轻量级进程(lightweight processes),但轻量级进程更多指的是内核线程(kernel thread),而把用户线程(user thread)称为线程。

> “进程------资源分配的最小单位,线程------程序执行的最小单位。”

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

面试部分之使用线程的理由
从上面我们知道了进程与线程的区别,其实这些区别也就是我们使用线程的理由。总的来说就是:进程有独立的地址空间,线程没有单独的地址空间(同一进程内的线程共享进程的地址空间)。
使用多线程的理由之一是和进程相比,它是一种非常"节俭"的多任务操作方式。我们知道,在Linux系统下,启动一个新的进程必须分配给它独立的地址空间,建立众多的数据表来维护它的代码段、堆栈段和数据段,这是一种"昂贵"的多任务工作方式。而运行于一个进程中的多个线程,它们彼此之间使用相同的地址空间,共享大部分数据,启动一个线程所花费的空间远远小于启动一个进程所花费的空间,而且,线程间彼此切换所需的时间也远远小于进程间切换所需要的时间。据统计,总的说来,一个进程的开销大约是一个线程开销的30倍左右,当然,在具体的系统上,这个数据可能会有较大的区别。
使用多线程的理由之二是线程间方便的通信机制。对不同进程来说,它们具有独立的数据空间,要进行数据的传递只能通过通信的方式进行,这种方式不仅费时,而且很不方便。线程则不然,由于同一进程下的线程之间共享数据空间,所以一个线程的数据可以直接为其它线程所用,这不仅快捷,而且方便。当然,数据的共享也带来其他一些问题,有的变量不能同时被两个线程所修改,有的子程序中声明为static的数据更有可能给多线程程序带来灾难性的打击,这些正是编写多线程程序时最需要注意的地方。

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

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

与线程相关API详解:
1.线程的创建
函数原型:

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.线程退出
函数原型:

int pthread_exit(void *rval_ptr);

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

退出的方式:
单个线程可以通过以下三种方式退出,在不终止整个进程的情况下停止它的控制流:
  1)线程只是从启动例程中返回,返回值是线程的退出码。
  2)线程可以被同一进程中的其他线程取消。
  3)线程调用pthread_exit:

3.线程等待
函数原型:

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.线程脱离
函数原型:
pthread_detach函数把指定的线程转变为脱离状态。

int pthread_detach(pthread_t thread);

返回值:若成功返回0,否则返回错误编号

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

pthread_detach(pthread_self());

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

5.线程ID获取及比较
函数原型:

pthread_t pthread_self(void);

返回值:调用线程的ID

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

int pthread_equal(pthread_t tid1, pthread_t tid2);

返回值:若相等则返回非0值,否则返回0

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

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

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

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

1.创建及销毁互斥锁
函数原型:

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.加锁及解锁  
函数原型:

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

与条件变量相关的API
条件变量是线程另一可用的同步机制。条件变量给多个线程提供了一个会合的场所。条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。

条件本身是由互斥量保护的。线程在改变条件状态前必须首先锁住互斥量,其他线程在获得互斥量之前不会察觉到这种改变,因为必须锁定互斥量以后才能计算条件。

条件变量使用之前必须首先初始化,pthread_cond_t数据类型代表的条件变量可以用两种方式进行初始化,可以把常量PTHREAD_COND_INITIALIZER赋给静态分配的条件变量,但是如果条件变量是动态分配的,可以使用pthread_cond_destroy函数对条件变量进行去除初始化(deinitialize)。

1.创建及销毁条件变量
函数原型:

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

2.等待
函数原型:

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函数类似,只是多了一个timeouttimeout指定了等待的时间,它是通过timespec结构指定。

3.触发
函数原型:

int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);

返回值:若成功返回0,否则返回错误编号

这两个函数可以用于通知线程条件已经满足。pthread_cond_signal函数将唤醒等待该条件的某个线程,而pthread_cond_broadcast函数将唤醒等待该条件的所有进程。

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

在上面理论知识已经介绍的差不多了,那么现在我们来实战一下,看一下代码示例:
demo1.c
demo1是简单的创建线程并等待

#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:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("the arg is:%d\n",*((int *)arg));

        pthread_exit(NULL);
}

int main()
{
    
    
        pthread_t t1;
        int ret;
        int param = 12;

        ret = pthread_create(&t1,NULL,func1,(int *)&param);
        if(ret == 0)
        {
    
    
                printf("Success to create the t1 pthread\n");
        }
        printf("main:the id:%ld\n",(unsigned long)pthread_self());
        pthread_join(t1,NULL);
        return 0;
}

结果:

CLC@Embed_Learn:~/SECOND/THREAD$ ./a.out 
Success to create the t1 pthread
main:the id:139736122025728
t1:the id of the pthread is:139736113739520
the arg is:12

demo2.c
demo2是在demo1的基础上实现了主线程等待时实现接收线程返回的值

#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 ret = 13;
        printf("t1:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("the arg is:%d\n",*((int *)arg));

        pthread_exit((void *)&ret);
}

int main()
{
    
    
        pthread_t t1;
        int ret;
        int param = 12;
        int *pret = NULL;

        ret = pthread_create(&t1,NULL,func1,(int *)&param);
        if(ret == 0)
        {
    
    
              printf("Success to create the t1 pthread\n");
        }

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

        pthread_join(t1,(void **)&pret);
        printf("the pret is:%d\n",*pret);

        return 0;
}

结果:

CLC@Embed_Learn:~/SECOND/THREAD$ ./a.out
Success to create the t1 pthread
main:the id:139775874971392
t1:the id of the pthread is:139775866685184
the arg is:12
the pret is:13

demo3.c
demo3其实跟demo2一样,只是demo3返回的是字符串

#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 *ret = "the t1 is Quit!";

        printf("t1:the id of t1 is:%ld\n",(unsigned long)pthread_self());
        printf("t1:the arg is:%d\n",*((int *)arg));

        pthread_exit((void *)ret);
}

int main()
{
    
    
        pthread_t t1;
        int param = 13;
        int ret;
        char *pret = NULL;

        ret = pthread_create(&t1,NULL,func1,(int *)&param);
        if(ret == 0)
        {
    
    
                printf("Success to create the t1\n");
        }

        int set = pthread_join(t1,(void **)&pret);

        printf("set is :%d\n",set);
        printf("main:the id of the main is:%ld\n",(unsigned long)pthread_self());

        printf("t1:the pret is:%s\n",pret);
        return 0;
}

结果:

CLC@Embed_Learn:~/SECOND/THREAD$ ./a.out 
Success to create the t1
t1:the id of t1 is:140599109383936
t1:the arg is:13
set is :0
main:the id of the main is:140599117670144
t1:the pret is:the t1 is Quit!

demo4.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 r_data = 0;

void *func1(void *arg)
{
    
    
        printf("t1:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t1:the arg is:%d\n",*((int *)arg));

        while(1)
        {
    
    
                printf("t1:the r_data is:%d\n",r_data++);
                sleep(1);
        }

        pthread_exit(NULL);
}

void *func2(void *arg)
{
    
    
        printf("t2:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t2:the arg is:%d\n",*((int *)arg));

        while(1)
        {
    
    
                printf("t2:the r_data is:%d\n",r_data++);
                sleep(1);
        }

        pthread_exit(NULL);
}

int main()
{
    
    
        pthread_t t1;
        pthread_t t2;
        int ret1;
        int ret2;
        int param = 12;

        ret1 = pthread_create(&t1,NULL,func1,(int *)&param);
        if(ret1 == 0)
        {
    
    
                printf("Success to create the t1 pthread\n");
        }

        ret2 = pthread_create(&t2,NULL,func2,(int *)&param);
        if(ret2 == 0)
        {
    
    
                printf("Success to create the t2 pthread\n");
        }

        while(1)
        {
    
    
                printf("main:the r_data is:%d\n",r_data++);
                sleep(1);
        }

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

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

        return 0;
}

结果:

CLC@Embed_Learn:~/SECOND/THREAD$ ./a.out
Success to create the t1 pthread
t1:the id of the pthread is:140586490631936
t1:the arg is:12
t1:the r_data is:0
Success to create the t2 pthread
main:the r_data is:1
t2:the id of the pthread is:140586482239232
t2:the arg is:12
t2:the r_data is:2
t1:the r_data is:3
main:the r_data is:4
t2:the r_data is:5

demo5.c
demo5是互斥锁的实现,仔细观察被锁住的内容的运行状态,那个线程先运行还是随机的(即线程对系统资源的抢占),但被锁住的内容是先执行完了,才会执行其他线程的内容

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

//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//                   void *(*start_routine) (void *), void *arg);

int r_data = 0;

pthread_mutex_t mutex;

void *func1(void *arg)
{
    
    
        pthread_mutex_lock(&mutex);

        printf("t1:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t1:the arg is:%d\n",*((int *)arg));
        //sleep(1);
        //pthread_exit(NULL);
        pthread_mutex_unlock(&mutex);
}

void *func2(void *arg)
{
    
    
        pthread_mutex_lock(&mutex);
		printf("t2:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t2:the arg is:%d\n",*((int *)arg));
        //sleep(1);
        //pthread_exit(NULL);

        pthread_mutex_unlock(&mutex);
}

void *func3(void *arg)
{
    
    
        pthread_mutex_lock(&mutex);
        int i;

        for(i = 0;i < 3;i++)
        {
    
    
         printf("t3:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
         printf("t3:the arg is:%d\n",*((int *)arg));
         sleep(1);
         }
         pthread_mutex_unlock(&mutex);
}

int main()
{
    
    
        pthread_t t1;
        pthread_t t2;
        pthread_t t3;
        int ret1;
        int ret2;
        int ret3;
        int param = 12;

        pthread_mutex_init(&mutex,NULL);

        ret1 = pthread_create(&t1,NULL,func1,(int *)&param);
        if(ret1 == 0)
        {
    
    
               printf("Success to create the t1 pthread\n");
        }

        ret2 = pthread_create(&t2,NULL,func2,(int *)&param);
        if(ret2 == 0)
        {
    
    
               printf("Success to create the t2 pthread\n");
        }

        ret3 = pthread_create(&t3,NULL,func3,(int *)&param);
        if(ret3 == 0)
        {
    
    
                printf("Success to create the t3 pthread\n");
        }

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

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

        pthread_mutex_destroy(&mutex);
        return 0;
}

结果:

CLC@Embed_Learn:~/SECOND/THREAD$ ./a.out 
Success to create the t1 pthread
Success to create the t2 pthread
t1:the id of the pthread is:139960549082880
t1:the arg is:12
Success to create the t3 pthread
main:the id:139960557369088
t3:the id of the pthread is:139960532297472
t3:the arg is:12
t3:the id of the pthread is:139960532297472
t3:the arg is:12
t3:the id of the pthread is:139960532297472
t3:the arg is:12
t2:the id of the pthread is:139960540690176
t2:the arg is:12

demo6.c
demo6是通过锁的方式来让data的某一个值被特定的线程所执行,但是这样带有一定的随机性,因为不知道是哪个线程先抢到资源先。

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

//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//                   void *(*start_routine) (void *), void *arg);

int r_data = 0;

pthread_mutex_t mutex;

void *func1(void *arg)
{
    
    
        printf("t1:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t1:the arg is:%d\n",*((int *)arg));

        pthread_mutex_lock(&mutex);
        while(1)
        {
    
    
                printf("t1:the r_data is:%d\n",r_data++);
                sleep(1);

                if(r_data == 3)
                {
    
    
                        pthread_mutex_unlock(&mutex);
                        printf("t1 is Quit ========!!!!!\n");
                        pthread_exit(NULL);
                }
        }
}

void *func2(void *arg)
{
    
    
        printf("t2:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t2:the arg is:%d\n",*((int *)arg));

        while(1)
        {
    
    
                printf("t2:the r_data is:%d\n",r_data);
                pthread_mutex_lock(&mutex);
                r_data++;
                pthread_mutex_unlock(&mutex);

                sleep(1);
        }

        pthread_exit(NULL);
}

int main()
{
    
    
        pthread_t t1;
        pthread_t t2;
        int ret1;
        int ret2;
        int param = 12;

        pthread_mutex_init(&mutex,NULL);

        ret1 = pthread_create(&t1,NULL,func1,(int *)&param);
        if(ret1 == 0)
        {
    
    
                printf("Success to create the t1 pthread\n");
        }

        ret2 = pthread_create(&t2,NULL,func2,(int *)&param);
        if(ret2 == 0)
        {
    
    
                printf("Success to create the t2 pthread\n");
        }
        
        while(1)
        {
    
    
                printf("main:the r_data is:%d\n",r_data);
                sleep(1);
        }

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

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

        pthread_mutex_destroy(&mutex);
        return 0;
}

结果:

CLC@Embed_Learn:~/SECOND/THREAD$ ./a.out
Success to create the t1 pthread
Success to create the t2 pthread
main:the r_data is:0
t1:the id of the pthread is:139801835206400
t1:the arg is:12
t1:the r_data is:0
t2:the id of the pthread is:139801826813696
t2:the arg is:12
t2:the r_data is:1
main:the r_data is:1
t1:the r_data is:1
main:the r_data is:2
t1:the r_data is:2
main:the r_data is:3
t1 is Quit ========!!!!!
t2:the r_data is:4
main:the r_data is:5

demo7.c
死锁可能面试会问,死锁的意思就是两把锁,线程A握住一把锁想去拿第二把锁,线程B拿着第二把锁想去拿第一把锁,谁都不让谁,所以导致程序处于阻塞停止不前的状态。
demo7主要讲解的时候导致死锁的问题。

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

//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//                   void *(*start_routine) (void *), void *arg);

int r_data = 0;

pthread_mutex_t mutex;
pthread_mutex_t mutex2;

void *func1(void *arg)
{
    
    
        pthread_mutex_lock(&mutex);
        sleep(1);
        pthread_mutex_lock(&mutex2);

        printf("t1:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t1:the arg is:%d\n",*((int *)arg));
        //sleep(1);
        //pthread_exit(NULL);
        pthread_mutex_unlock(&mutex);
}

void *func2(void *arg)
{
    
    
        pthread_mutex_lock(&mutex2);
        sleep(1);
        pthread_mutex_lock(&mutex);

        printf("t2:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t2:the arg is:%d\n",*((int *)arg));
        //sleep(1);
        //pthread_exit(NULL);

        pthread_mutex_unlock(&mutex);
}

void *func3(void *arg)
{
    
    
        pthread_mutex_lock(&mutex);
        int i;

        for(i = 0;i < 3;i++)
        {
    
    
         printf("t3:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
         printf("t3:the arg is:%d\n",*((int *)arg));
         sleep(1);
        }
         pthread_mutex_unlock(&mutex);
}

int main()
{
    
    
        pthread_t t1;
        pthread_t t2;
        pthread_t t3;
        int ret1;
        int ret2;
        int ret3;
        int param = 12;
        
        pthread_mutex_init(&mutex,NULL);
        pthread_mutex_init(&mutex2,NULL);

        ret1 = pthread_create(&t1,NULL,func1,(int *)&param);
        if(ret1 == 0)
        {
    
    
                printf("Success to create the t1 pthread\n");
        }

        ret2 = pthread_create(&t2,NULL,func2,(int *)&param);
        if(ret2 == 0)
        {
    
    
                printf("Success to create the t2 pthread\n");
        }

        ret3 = pthread_create(&t3,NULL,func3,(int *)&param);
        if(ret3 == 0)
        {
    
    
                printf("Success to create the t3 pthread\n");
        }
        printf("main:the id:%ld\n",(unsigned long)pthread_self());

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

        pthread_mutex_destroy(&mutex);
        pthread_mutex_destroy(&mutex2);

        return 0;
}

结果:
在这里插入图片描述
由结果可以看出,程序卡在了那里,执行不下去了,所以这就是导致了死锁的发生

demo8.c
demo8使用了条件变量中的等待与触发来实现当data到达某个值的时候让特定的线程来执行

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

//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//                   void *(*start_routine) (void *), void *arg);

int r_data = 0;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *func1(void *arg)
{
    
    
        printf("t1:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t1:the arg is:%d\n",*((int *)arg));

        while(1)
        {
    
    
                pthread_cond_wait(&cond,&mutex);
                printf("t1:the r_data is:%d\n",r_data);
                printf("t1 is run ========!!!!!\n");

                r_data = 0;
                sleep(1);
         }
}

void *func2(void *arg)
{
    
    
        printf("t2:the id of the pthread is:%ld\n",(unsigned long)pthread_self());
        printf("t2:the arg is:%d\n",*((int *)arg));

        while(1)
        {
    
    
                printf("t2:the r_data is:%d\n",r_data);
                pthread_mutex_lock(&mutex);
                r_data++;
                if(r_data == 3)
                {
    
    
                        pthread_cond_signal(&cond);
                }

                sleep(1);
                pthread_mutex_unlock(&mutex);
        }
}

int main()
{
    
    
        pthread_t t1;
        pthread_t t2;
        int ret1;
        int ret2;
        int param = 12;

        pthread_mutex_init(&mutex,NULL);
        pthread_cond_init(&cond,NULL);

        ret1 = pthread_create(&t1,NULL,func1,(int *)&param);
        if(ret1 == 0)
        {
    
    
//              printf("Success to create the t1 pthread\n");
        }

        ret2 = pthread_create(&t2,NULL,func2,(int *)&param);
        if(ret2 == 0)
        {
    
    
//              printf("Success to create the t2 pthread\n");
        }

/*      while(1)
        {
                printf("main:the r_data is:%d\n",r_data);
                sleep(1);
        }
*/
        printf("main:the id:%ld\n",(unsigned long)pthread_self());

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

        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&cond);

        return 0;
}

针对linux多线程,使用了8个demo来进行说明与学习

学习笔记,仅供参考

猜你喜欢

转载自blog.csdn.net/weixin_51976284/article/details/124852455