首页 > 其他分享 >线程同步:锁,条件变量,并发

线程同步:锁,条件变量,并发

时间:2024-09-23 17:25:13浏览次数:1  
标签:std 同步 get int 并发 future 线程 promise

1)锁mutex

2)条件变量
头文件<condiction_variable>
condition_variable cv;
cv.wait(_lock,谓语)//使用谓语检查是否满足唤醒条件,防止假唤醒

using namespace std;
	mutex _mutex;
	condition_variable cv;
	//condition_variable cv2;
	int num = 1;

	thread th1([&]() {
		int i = 10;
		while (i--)
		{
			std::unique_lock<std::mutex> lock(_mutex);
			cv.wait(lock, [&]() {
				return num == 1;
			});
			cout << "one" << endl;
			num = 2;
			cv.notify_one();
		}

		
	});

	thread th2([&]() {
		int i = 10;
		while (i--)
		{
			std::unique_lock<std::mutex> lock(_mutex);
			cv.wait(lock, [&]() {
				return num == 2;
			});
			cout << "two" << endl;
			num = 1;
			cv.notify_one();
		}
		
		
	});

	th1.join();
	th2.join();

3)并发三剑客, future, promise以及async

async:
不开线程,异步调用一个函数(其实是默认开启后台线程)

int fun_task(int val)
{
	int i = 4;
	while (i--)
	{
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
	return 12;
}

//异步调用一个函数
int main(int argc,char* argv[])
{
	using namespace std;

	std::future<int> result = std::async(std::launch::async, fun_task, 4);

	for (int i = 0; i < 4; i++)
	{
		std::this_thread::sleep_for(std::chrono::seconds(1));
		std::cout << i << std::endl;
	}
	int _val= result.get();
	cout << _val << endl;

// 使用 std::async 异步调用 fetchDataFromDB
std::futurestd::string resultFromDB = std::async(std::launch::async, fetchDataFromDB, "Data");

std::launch枚举:
std::launch::deferred:这种策略意味着任务将在调用std::future::get()或std::future::wait()函数时延迟执行。换句话说,任务将在需要结果时同步执行。
std::launch::async 标志来明确表明我们希望函数异步执行。
std::launch::async | std::launch::deferred:(默认值)这种策略是上面两个策略的组合。任务可以在一个单独的线程上异步执行,也可以延迟执行,具体取决于实现。

4)std::promise
std::promise 和 std::future 一起使用,可以实现从一个线程向另一个线程传递值或异常的功能。

void producer(std::promise<int> &&promise) {
    // 模拟耗时操作
    std::this_thread::sleep_for(std::chrono::seconds(2));
    int result = 42;
    promise.set_value(result); // 设置值
}

int main() {
    // 创建一个 promise 对象
    std::promise<int> promise;

    // 获取对应的 future 对象
    std::future<int> future = promise.get_future();

    // 在一个新线程中执行 producer 函数
    std::thread t(producer, std::move(promise));

    // 继续执行其他操作
    std::cout << "Doing some other work..." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // 获取异步任务的结果
    try {
        int result = future.get(); // 阻塞,直到结果可用
        std::cout << "Result: " << result << std::endl;
    } catch (const std::exception &e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    // 等待子线程完成
    t.join();

    return 0;

线程间通信的其他方式:
消息队列如 Boost.Interprocess
共享内存:Boost.Interprocess

5)std::future
包含:
std::future val;
std::shared_future val;共享类型future

std::future::get()/wait()

std::future::get() 是一个阻塞调用,用于获取 std::future 对象表示的值或异常。
如果异步任务还没有完成,get() 会阻塞当前线程,直到任务完成。如果任务已经完成,get() 会立即返回任务的结果
get()只能调用一次
如果有异常,get会抛出

std::future::wait() 也是一个阻塞调用,
如果任务已经完成,wait() 会立即返回。如果任务还没有完成,wait() 会阻塞当前线程,直到任务完成。与 get() 不同,wait() 可以被多次调用

b)获得处理异步任务的结果
std::packaged_task和std::future

标签:std,同步,get,int,并发,future,线程,promise
From: https://www.cnblogs.com/light-LifeClub/p/18427440

相关文章

  • 多线程问题:异常处理,单例
    1)多线程异常处理多线程中如何捕获抛出异常到主线程a)catch中使用std::current_exception();获得正在处理的异常b)通过引用类型std::exception_ptr&_ex_ptr传出c)std::rethrow_exception(ex_ptr);重新抛出异常usingnamespacestd; try{ std::exception_ptrex_ptr;......
  • 主从数据库同步配置详解(MySQL/MariaDB)
    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录前言一、环境准备与安装配置本地部署MySQLUbuntu系统:CentOS系统:MariaDBUbuntu系统:CentOS系统:容器部署MySQLMariaDB二、配置主从库的同步设置四、测试与维护总结前言在数据库管理中,......
  • Java 线程机制
    目录1进程和线程2串行、并行和并发3Java实现多线程的三种方法3.1继承 Thread 类3.2 实现 Runnable 接口3.3 实现 Callable 接口4线程常用API4.1设置优先级4.2线程休眠4.3线程让步4.4线程重点(加入)4.5线程中断4.6线程守护4.7获取线程ID4.8获......
  • locust+python高并发压测总结
    locust+python全链路压测总结1.什么是接口?为系统提供数据服务的叫做接口(Interface)locust安装pipinstalllocust安装完成后:locust-h查看是否安装成功2.如何编写locust脚本?编写locust脚本主要分为以下几个步骤:导入Locust类定义用户行为定义任务运行脚本2.1导入Lo......
  • 面试:多线程顺序打印
            在多线程中有多种方法让线程按特定顺序执行,可以用线程类的join()方法在一个线程中启动另一个线程,另外一个线程完成该线程继续执行。比如说:使用join方法,T3调用T2,T2调用T1,这样就能确保T1就会先完成而T3最后完成。        定义三个类,分别实现Runnable接......
  • c++多线程,锁
    1)机器最大线程数uint16_tmax_thread=thread::hardware_concurrency();2)vector中管理线程获取线程ida)thread::id_id=std::this_thread::get_id();b)threadth(getSum_vector,ref(arr),ref(_sum));cout<<th.get_id();容器中存储线程变量:使用emplace_back原位构造a......
  • SpringBoot + Disruptor 实现特快高并发处理,支撑每秒 600 万订单无压力!
    01、背景02、Disruptor介绍03、Disruptor的核心概念04、RingBuffer05、SequenceDisruptor06、Sequencer07、SequenceBarrier08、WaitStrategy09、Event10、EventProcessor11、EventHandler12、Producer13、案例-demo14、总结01、背景工作中遇到项目使用Di......
  • 关于Go的并发
    前面我们提到因为Go语言的高并发、高性能,所以选择Go,这次我们看看Go的高并发。并发编程关于并发和并行并发:早期计算机的CPU都是单核的,一个CPU在同一时间只能执行一个进程/线程,当系统中有多个进程/线程等待执行时,CPU只能执行完一个再执行下一个。简单来讲,并发就是多线......
  • paimon flink cdc 整库同步
    --单表同步bin/flinkrun/opt/module/flink/opt/paimon-flink-action-0.9.0.jarmysql-sync-table--warehousehdfs://xx:8020/paimon/hive--databasedefault--tableuser1_sink--primary-keysid--mysql-confhostname=xx--mysql-confusername=xx--mysql-conf......
  • HI8166 同步40V4A
    Hi8166isasynchronousrectifierfor switchmodepowersupplies,which combinesanN-ChannelMOSFETand adrivercircuitdesignedforsynchronous rectificationinDCM,QRandCCM operation. Thesynchronousrectificationcan effectivelyreducethese......