多线程编程——屏障

屏障是多线程同步的一种方法。barrier意为屏障或者栏杆,把先后到达的多个线程挡在同一栏杆前,直到所有线程到齐,然后撤下栏杆同时放行。先到达的线程将会阻塞,等到所有调用pthread_barrier_wait()函数的线程(数量等于屏障初始化时指定的count)都到达后,这些线程才会由阻塞状态进入就绪状态再次参与系统调度。屏障是基于条件变量和互斥锁实现的。主要操作包括:调用pthread_barrier_init()初始化一个屏障,其他线程调用pthread_barrier_wait(),所有线程到期后线程唤醒进入准备状态,屏障不在使用调用pthread_barrier_destroy()销毁一个屏障

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
/* 线程控制块 */
static pthread_t tid1;
static pthread_t tid2;
static pthread_t tid3;
/* 屏障控制块 */
static pthread_barrier_t barrier;
/* 函数返回值检查函数 */
static void check_result(char* str,int result)
{
	if (0 == result)
	{
		printf("%s successfully!\n",str);
	}
	else
	{
		printf("%s failed! error code is %d\n",str,result);
	}
}
/*线程1入口函数*/
static void* thread1_entry(void* parameter)
{
	int count = 0;
	printf("thread1 have arrived the barrier!\n");
	pthread_barrier_wait(&barrier); /* 到达屏障,并等待其他线程到达 */
	while (1)
	{
		/* 打印线程计数值输出 */
		printf("thread1 count: %d\n",count ++);
		/* 休眠2秒*/
		sleep(2);
	}
}
/*线程2入口函数*/
static void* thread2_entry(void* parameter)
{
	int count = 0;
	printf("thread2 have arrived the barrier!\n");
	pthread_barrier_wait(&barrier);
	while (1)
	{
		/* 打印线程计数值输出 */
		printf("thread2 count: %d\n",count ++);
		/* 休眠2秒*/
		sleep(2);
	}
}
/* 线程3入口函数 */
static void* thread3_entry(void* parameter)
{
	int count = 0;
	printf("thread3 have arrived the barrier!\n");
	pthread_barrier_wait(&barrier);
	while (1)
	{
		/* 打印线程计数值输出 */
		printf("thread3 count: %d\n",count ++);
		/* 休眠2秒*/
		sleep(2);
	}
}
/* 用户应用入口 */
int application_init()
{
	int result;
	pthread_barrier_init(&barrier,NULL,3);
	/*创建线程1,线程入口是thread1_entry, 属性参数设为NULL选择默认值,入口参数为NULL*/
	result = pthread_create(&tid1,NULL,thread1_entry,NULL);
	check_result("thread1 created",result);
	/*创建线程2,线程入口是thread2_entry, 属性参数设为NULL选择默认值,入口参数为NULL*/
	result = pthread_create(&tid2,NULL,thread2_entry,NULL);
	check_result("thread2 created",result);
	/*创建线程3,线程入口是thread3_entry, 属性参数设为NULL选择默认值,入口参数为NULL*/
	result = pthread_create(&tid3,NULL,thread3_entry,NULL);
	check_result("thread3 created",result);
	
	
	return 0;
}
int main()
{
	int i ;
	application_init();
	i=100;
	do{
		sleep(1);
	}while(i--);
}

运行结果:

-bash-3.2$ gcc -pthread barrier.c -o 8app
-bash-3.2$ ./8app
thread1 created successfully!
thread2 created successfully!
thread3 created successfully!
thread1 have arrived the barrier!
thread2 have arrived the barrier!
thread3 have arrived the barrier!
thread1 count: 0
thread2 count: 0
thread3 count: 0
thread1 count: 1
thread2 count: 1
thread3 count: 1
thread1 count: 2
thread2 count: 2
thread3 count: 2
thread2 count: 3
thread3 count: 3
thread1 count: 3
thread2 count: 4
thread3 count: 4
thread1 count: 4
thread2 count: 5
thread3 count: 5
thread1 count: 5
thread2 count: 6
thread3 count: 6
thread1 count: 6
thread2 count: 7
thread3 count: 7
thread1 count: 7
thread2 count: 8
thread3 count: 8
thread1 count: 8
thread2 count: 9
thread3 count: 9
thread1 count: 9

### Java多线程编程与并发处理概述 Java 中的多线程编程和并发处理是一个复杂而重要的主题,它涉及多个方面,包括但不限于线程的创建、生命周期管理、同步机制以及高级工具的应用。以下是关于这些方面的详细介绍。 #### 线程的创建与生命周期 在 Java 中,可以通过继承 `Thread` 类或者实现 `Runnable` 接口来创建线程。每种方式都有其适用场景,通常推荐使用 `Runnable` 接口以支持更灵活的设计模式[^1]。 线程的状态转换遵循 JVM 定义的标准模型,主要包括新建 (New)、可运行 (Runnable)、阻塞 (Blocked)、等待 (Waiting/Timed Waiting) 和终止 (Terminated)[^5]。 #### 线程同步与锁机制 为了防止多个线程同时访问共享资源而导致数据不一致的问题,可以采用多种同步手段。最常见的方式是通过关键字 `synchronized` 来定义临界区或方法;此外还可以利用显式的锁对象 (`Lock`) 提供更高的灵活性和功能扩展能力。 #### 高级并发工具 除了基本的线程控制外,JDK 还提供了一系列丰富的 API 支持复杂的并发操作需求,比如原子变量(`AtomicInteger`, etc.)、信号量(Semaphore)、屏障(CyclicBarrier/CountDownLatch)等。 --- ### 线程池的概念及其重要性 直接频繁地创建销毁大量短命的工作线程不仅消耗系统资源而且效率低下,因此引入了 **线程池** 技术作为解决方案之一。它可以有效减少因反复建立新连接所带来的开销并提升整体吞吐率[^2]。 #### 常见类型的线程池 根据不同的应用场景可以选择合适的预定义好的几种固定形式: - 单一线程池(Single Thread Executor) - 固定大小线程池(Fixed Thread Pool) - 可缓存线程池(Cached Thread Pool) - 计划任务调度器(Scheduled Executor Service) 上述各类均封装于 Executors 工厂类之下便于快速实例化调用[^3]。 #### ThreadPoolExecutor 的工作原理 实际上所有的标准线程池最终都依赖于核心类——ThreadPoolExecutor 来完成具体的逻辑运作。该类允许开发者自定义诸如最大最小活跃数目的界限参数从而精确调整行为表现满足特定条件下的负载平衡要求[^4]。 ```java // 创建一个具有指定配置选项的核心线程池示例代码片段 import java.util.concurrent.*; public class CustomThreadPoolExample { public static void main(String[] args){ int corePoolSize = 5; int maximumPoolSize = 10; long keepAliveTime = 5L; ThreadPoolExecutor executorService = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>() ); // Submit tasks to the pool... executorService.shutdown(); // Gracefully shutdown after all jobs done. } } ``` --- ### 最佳实践建议 1. 尽可能重用已存在的线程而不是每次都重新生成新的; 2. 合理设置初始容量避免过高过低影响性能稳定性; 3. 对异常情况进行捕获记录以便后续排查定位问题所在位置; 4. 使用 try-finally 结构确保最后能够正确释放掉所占用的所有外部链接资源。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值