zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Linux多线程信号量控制手段!

2023-03-07 09:07:56 时间

一. Linux多线程DEMO介绍:

本次的DEMO是对多线程知识点的回顾,因为多线程技术在我们平常开发中经常用到。这次的DEMO是通过发送信号量去控制线程的运行和停止。相当于我们通过输入一个指令让某个线程启动和停止。

二. 整个DEMO的流程框图

三.整个DEMO的代码模块

3.1. process1_threadprocess2_thread线程的讲解:

process1_thread线程和process2_thread线程,分别用blocking_thread_wait函数进行阻塞。相当于这两个线程默认是挂起阻塞起来,然后等着input_monitor线程发送指令。process1_thread线程主要由g_blocking_thread_01变量去控制它的运行状态,process21_thread线程则是由g_blocking_thread_02变量去控制它的运行状态。

3.2. input_monitor线程的讲解:

input_monitor线程的主要用途是,发送指令去操控process1_thread线程和process2_thread线程的运行。input_monitor总共可以操控四个指令分别是:start_01指令、stop_01指令、start_02指令、stop_02指令。

start_01指令:主要是利用blocking_thread_start去启动process_thread1线程,此时process1_thread线程将会不断打印Process1_Thread字段。

stop_01指令:主要是利用blocking_thread_stop去启动process_thread1线程,此时process1_thread线程将会停止打印Process1_Thread字段。

start_02指令:主要是利用blocking_thread_start去启动process_thread2线程,此时process2_thread线程将会不断打印Process02_Thread字段。

stop_02指令:主要是利用blocking_thread_stop去启动process_thread2线程,此时process2_thread线程将会停止打印Process2_Thread字段。

3.3. 线程控制模块blocking_thread_unit.c的讲解:

blocking_thread_unit.c分别有三个函数,分别是: blocking_thread_wait、blocking_thread_start、blocking_thread_stop。

blocking_thread_wait主要功能是:等待线程阻塞,若收到的count一直是0则会一直阻塞在那里,若收到一个非0的值则会解除阻塞,让线程往下走。使用的api是pthread_cond_wait线程等待函数。

blocking_thread_start主要功能是:开启对应的线程,把线程的count设置成1,并且使用pthread_cond_broadcast去通知对应的线程,要开始线程的打印。

blocking_thread_stop主要功能是:停止对应的线程,把线程的count设置成0,并且使用pthread_cond_broadcast去通知对应的线程,要停止线程的打印。

g_blocking_thread_01g_blocking_thread_02两个全局变量的讲解:

这里的控制线程主要用到了两个全局变量对两个线程进行控制,分别是g_blocking_thread_01g_blocking_thread_02g_blocking_thread_01主要是控制process1_thread线程的停止和开启,g_blocking_thread_02主要是控制process2_thread线程的开启和停止。

四.整个DEMO工程的代码: