C++ 并发支持库 (线程 原子操作 条件变量 信号量)

文章介绍了C++中使用原子操作进行并发编程的方法,包括使用`std::atomic`实现原子变量,以及在多线程环境下利用`pthread_cond_timedwait`进行条件等待的例子。示例代码展示了如何避免数据竞争,实现线程安全的计数器增量操作。
摘要由CSDN通过智能技术生成


sem_t sem[PLATMAX_NUM];
sem_t sem_plt;
pthread_mutex_t v2x_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_plat = PTHREAD_COND_INITIALIZER; 


struct timeval now;
struct timespec outtime;
while(appd_run_flag.appd_pltfrm_flag==1&&v2x_flag==0)
{
 	gettimeofday(&now, NULL);
  		outtime.tv_sec = now.tv_sec + WAIT_TIME;
  		outtime.tv_nsec = now.tv_usec * 1000;
	ret = pthread_cond_timedwait(&cond_plat, &v2x_mutex, &outtime);
	if(ret!=0)

	{
		SPS_LOG_DEBUG_FMT("cond_plt wait timout,ret:%d",ret);
	}
	else
	{
		SPS_LOG_DEBUG_FMT("cond_plt get_v2xINfo,ret:%d",ret);
		break;
	}
	v2x_flag=rsi_flag.plt_flag+rsm_flag.plt_flag+spat_flag.plt_flag+map_flag.plt_flag+bsm_flag.plt_flag+vehicle_flag.plt_flag+obj_flag.plt_flag+preempt_flag.plt_flag;
}
//清空标识、区

C++ 参考手册

原子操作

这些组建为细粒度的原子操作提供,允许无锁并发编程。涉及同一对象的每个原子操作,相对于任何其他原子操作是不可分的。原子对象不具有数据竞争。

#include <iostream>
#include <thread>
#include <atomic>
#include <functional>
using namespace std;

struct Counter
{
    void increment()
    {
        for (int i = 0; i < 10; ++i)
        {
            m_value++;
            cout << "increment number: " << m_value
                << ", theadID: " << this_thread::get_id() << endl;
            this_thread::sleep_for(chrono::milliseconds(500));
        }
    }
    // atomic<int> == atomic_int
    atomic_int m_value;
};

int main()
{
    Counter c;
    c.m_value = 0;
    auto increment = bind(&Counter::increment, &c);
    thread t1(increment);

    t1.join();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值