• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ std::atomic类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中std::atomic的典型用法代码示例。如果您正苦于以下问题:C++ atomic类的具体用法?C++ atomic怎么用?C++ atomic使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了atomic类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: try_lock

/** @brief a test-and-test-and-set lock */
class tatas_lock {
	std::atomic<bool> locked; /* TODO can std::atomic_flag be used? */
	public:
		tatas_lock() : locked(false) {};
		tatas_lock(tatas_lock&) = delete; /* TODO? */
		bool try_lock() {
			if(is_locked()) return false;
			return !locked.exchange(true, std::memory_order_acq_rel);
		}
开发者ID:davidklaftenegger,项目名称:qd_library,代码行数:10,代码来源:tatas_lock.hpp


示例2: globalManager

namespace folly {

std::atomic<EventBaseManager*> globalManager(nullptr);

EventBaseManager* EventBaseManager::get() {
  EventBaseManager* mgr = globalManager;
  if (mgr) {
    return mgr;
  }

  EventBaseManager* new_mgr = new EventBaseManager;
  bool exchanged = globalManager.compare_exchange_strong(mgr, new_mgr);
  if (!exchanged) {
    delete new_mgr;
    return mgr;
  } else {
    return new_mgr;
  }

}

/*
 * EventBaseManager methods
 */

void EventBaseManager::setEventBase(EventBase *eventBase,
                                     bool takeOwnership) {
  EventBaseInfo *info = localStore_.get();
  if (info != nullptr) {
    throw std::runtime_error("EventBaseManager: cannot set a new EventBase "
                             "for this thread when one already exists");
  }

  info = new EventBaseInfo(eventBase, takeOwnership);
  localStore_.reset(info);
  this->trackEventBase(eventBase);
}

void EventBaseManager::clearEventBase() {
  EventBaseInfo *info = localStore_.get();
  if (info != nullptr) {
    this->untrackEventBase(info->eventBase);
    this->localStore_.reset(nullptr);
  }
}

// XXX should this really be "const"?
EventBase * EventBaseManager::getEventBase() const {
  // have one?
  auto *info = localStore_.get();
  if (! info) {
    info = new EventBaseInfo();
    localStore_.reset(info);

    if (observer_) {
      info->eventBase->setObserver(observer_);
    }

    // start tracking the event base
    // XXX
    // note: ugly cast because this does something mutable
    // even though this method is defined as "const".
    // Simply removing the const causes trouble all over fbcode;
    // lots of services build a const EventBaseManager and errors
    // abound when we make this non-const.
    (const_cast<EventBaseManager *>(this))->trackEventBase(info->eventBase);
  }

  return info->eventBase;
}

} // namespace folly
开发者ID:SocialExplorerFork,项目名称:folly,代码行数:72,代码来源:EventBaseManager.cpp


示例3: recordPerfRelocMap

namespace HPHP { namespace jit { namespace tc {

void recordPerfRelocMap(
    TCA start, TCA end,
    TCA coldStart, TCA coldEnd,
    SrcKey sk, int argNum,
    const GrowableVector<IncomingBranch> &incomingBranchesIn,
    CGMeta& fixups) {
  String info = perfRelocMapInfo(start, end,
                                 coldStart, coldEnd,
                                 sk, argNum,
                                 incomingBranchesIn,
                                 fixups);
  Debug::DebugInfo::Get()->recordRelocMap(start, end, info);
}

void recordRelocationMetaData(SrcKey sk, SrcRec& srcRec, const TransLoc& loc,
                              CGMeta& fixups) {
  if (!RuntimeOption::EvalPerfRelocate) return;

  recordPerfRelocMap(loc.mainStart(), loc.mainEnd(),
                     loc.coldCodeStart(), loc.coldEnd(),
                     sk, -1,
                     srcRec.tailFallbackJumps(),
                     fixups);
}

static Debug::TCRange rangeFrom(const CodeBlock& cb, const TCA addr,
                                bool isAcold) {
  assertx(cb.contains(addr));
  return Debug::TCRange(addr, cb.frontier(), isAcold);
}

void recordGdbTranslation(SrcKey sk, const Func* srcFunc, const CodeBlock& cb,
                          const TCA start, bool exit, bool inPrologue) {
  if (start != cb.frontier()) {
    assertOwnsCodeLock();
    if (!RuntimeOption::EvalJitNoGdb) {
      Debug::DebugInfo::Get()->recordTracelet(
        rangeFrom(cb, start, &cb == &code().cold()),
        srcFunc,
        srcFunc->unit() ? srcFunc->unit()->at(sk.offset()) : nullptr,
        exit, inPrologue
      );
    }
    if (RuntimeOption::EvalPerfPidMap) {
      Debug::DebugInfo::Get()->recordPerfMap(
        rangeFrom(cb, start, &cb == &code().cold()),
        sk,
        srcFunc,
        exit,
        inPrologue
      );
    }
  }
}

void recordBCInstr(uint32_t op, const TCA addr, const TCA end, bool cold) {
  if (addr != end) {
    Debug::DebugInfo::Get()->recordBCInstr(Debug::TCRange(addr, end, cold), op);
  }
}

////////////////////////////////////////////////////////////////////////////////

static std::atomic<bool> s_loggedJitMature{false};

/*
 * If the jit maturity counter is enabled, update it with the current amount of
 * emitted code.
 */
void reportJitMaturity(const CodeCache& code) {
  auto static jitMaturityCounter = ServiceData::createCounter("jit.maturity");

  // Optimized translations are faster than profiling translations, which are
  // faster than the interpreter.  But when optimized translations are
  // generated, some profiling translations will become dead.  We assume the
  // incremental value of an optimized translation over the corresponding
  // profiling translations is comparable to the incremental value of a
  // profiling translation of similar size; thus we don't have to apply
  // different weights to code in different regions.
  auto const codeSize =
    code.hot().used() + code.main().used() + code.prof().used();
  if (jitMaturityCounter) {
    // EvalJitMatureSize is supposed to to be set to approximately 20% of the
    // code that will give us full performance, so recover the "fully mature"
    // size with some math.
    auto const fullSize = RuntimeOption::EvalJitMatureSize * 5;
    auto const after = codeSize >= fullSize ? 100
                                            : (codeSize * 100 / fullSize);
    auto const before = jitMaturityCounter->getValue();
    if (after > before) jitMaturityCounter->setValue(after);
  }

  if (!s_loggedJitMature.load(std::memory_order_relaxed) &&
      StructuredLog::enabled() &&
      codeSize >= RuntimeOption::EvalJitMatureSize &&
      !s_loggedJitMature.exchange(true, std::memory_order_relaxed)) {
    StructuredLogEntry cols;
    cols.setInt("jit_mature_sec", time(nullptr) - HttpServer::StartTime);
//.........这里部分代码省略.........
开发者ID:ezoic,项目名称:hhvm,代码行数:101,代码来源:tc-record.cpp


示例4: AtomWrapper

	AtomWrapper(const std::atomic<T> &a)
		:_a(a.load())
	{}
开发者ID:demyanenko,项目名称:Buddhabrot,代码行数:3,代码来源:atom_wrapper.hpp


示例5:

 inline bool operator !() const
 {
     return !m_value.load();
 }
开发者ID:cas4ey,项目名称:signals_library,代码行数:4,代码来源:mutex.hpp


示例6: is_locked

		bool is_locked() {
			return locked.load(std::memory_order_acquire);
		}
开发者ID:davidklaftenegger,项目名称:qd_library,代码行数:3,代码来源:tatas_lock.hpp


示例7: lock

 void lock()
 {
     while(mSpinLock.exchange(true) == true)
         SwitchToThread();
 }
开发者ID:Natman64,项目名称:d3dgl,代码行数:5,代码来源:commandqueue.hpp


示例8: getnature

	   /** getter for file nature */
	   inline NatureFlag getnature() { return m_filenature.load(std::memory_order_acquire); }
开发者ID:ImpalaToGo,项目名称:ImpalaToGo,代码行数:2,代码来源:managed-file.hpp


示例9: state

	   /** getter for File state */
	   inline State state() { return m_state.load(std::memory_order_acquire); }
开发者ID:ImpalaToGo,项目名称:ImpalaToGo,代码行数:2,代码来源:managed-file.hpp


示例10: nature

	   /** change the file nature */
	   inline void nature(NatureFlag nature = NatureFlag::PHYSICAL){ m_filenature.exchange(nature, std::memory_order_acq_rel); }
开发者ID:ImpalaToGo,项目名称:ImpalaToGo,代码行数:2,代码来源:managed-file.hpp


示例11: get

 T* get() const
 {
     return v.load(std::memory_order_consume);
 }
开发者ID:Hzj-jie,项目名称:osi,代码行数:4,代码来源:exclusive_container.hpp


示例12: Init

void SWRenderer::Init()
{
	s_bScreenshot.store(false);
}
开发者ID:BananaMuffinFrenzy,项目名称:dolphin,代码行数:4,代码来源:SWRenderer.cpp


示例13: SetScreenshot

void SWRenderer::SetScreenshot(const char *_szFilename)
{
	std::lock_guard<std::mutex> lk(s_criticalScreenshot);
	s_sScreenshotName = _szFilename;
	s_bScreenshot.store(true);
}
开发者ID:BananaMuffinFrenzy,项目名称:dolphin,代码行数:6,代码来源:SWRenderer.cpp


示例14:

	AtomWrapper & operator=(const AtomWrapper &other)
	{
		_a.store(other._a.load());
	}
开发者ID:demyanenko,项目名称:Buddhabrot,代码行数:4,代码来源:atom_wrapper.hpp


示例15: schedule

 void schedule (const Task & task)
 {
     POMAGMA_ASSERT(m_accepting.load(), "pool is not accepting work");
     m_queue.push(task);
     m_condition.notify_one();
 }
开发者ID:pomagma,项目名称:pomagma,代码行数:6,代码来源:worker_pool.hpp


示例16: main

int main() {

    try {

        SDLManager sdl{SDL_INIT_TIMER};
        sdl.setOpenGLVersion(3, 3);
        auto window = sdl.createWindow("Harken", 1024, 768);

        glewExperimental = true;
        const auto glewResult = glewInit();
        if (glewResult != GLEW_OK) {
            throw std::runtime_error{StringBuilder{} << "Could not initialise GLEW. Error: " << glewGetErrorString(glewResult)};
        }

        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

        VertexArrayObject triangleVAO;
        triangleVAO.bind();

        VertexBufferObject arrayBuffer{GL_ARRAY_BUFFER};
        arrayBuffer.bind();

        GLfloat vertices[3][2] = {
            { 0.0f,  0.433f},
            { 0.5f, -0.433f},
            {-0.5f, -0.433f}
        };

        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

        const auto vertexShader   = std::make_shared<Shader>(GL_VERTEX_SHADER, "uniform-scale.vert");
        const auto fragmentShader = std::make_shared<Shader>(GL_FRAGMENT_SHADER, "red.frag");

        ShaderProgram shaderProgram{vertexShader, fragmentShader};
        shaderProgram.use();

        glVertexAttribPointer(PositionAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
        glEnableVertexAttribArray(PositionAttrib);

        const auto scaleLocation = shaderProgram.uniformLocation("scale");

        SDL_AddTimer(1000 / 60, update, nullptr);

        auto running = true;
        while (running) {

            // TODO: move this into SDLManager

            SDL_Event event;
            while (SDL_PollEvent(&event)) {

                if (event.type == SDL_QUIT) {
                    running = false;
                }
            }

            glUniform1f(scaleLocation, std::sin(scale.load()));
            render(window, triangleVAO);
        }
    }
    catch (const std::exception& ex) {
        std::cout << ex.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
开发者ID:keystonerose,项目名称:harken,代码行数:67,代码来源:main.cpp


示例17: future_function_pointers

void future_function_pointers(Executor& exec)
{
    future_void_f1_count.store(0);
    future_void_f2_count.store(0);
    future_int_f1_count.store(0);
    future_int_f2_count.store(0);

    future<void> f1
        = dataflow(exec,
            &future_void_f1
          , async(&future_void_sf1, shared_future<void>(make_ready_future()))
        );

    f1.wait();

    HPX_TEST_EQ(future_void_f1_count, 2u);
    future_void_f1_count.store(0);

    future<void> f2 = dataflow(exec,
        &future_void_f2
      , async(&future_void_sf1, shared_future<void>(make_ready_future()))
      , async(&future_void_sf1, shared_future<void>(make_ready_future()))
    );

    f2.wait();
    HPX_TEST_EQ(future_void_f1_count, 2u);
    HPX_TEST_EQ(future_void_f2_count, 1u);

    future_void_f1_count.store(0);
    future_void_f2_count.store(0);
    future_int_f1_count.store(0);
    future_int_f2_count.store(0);

    future<int> f3 = dataflow(exec,
        &future_int_f1
      , make_ready_future()
    );

    HPX_TEST_EQ(f3.get(), 1);
    HPX_TEST_EQ(future_int_f1_count, 1u);
    future_int_f1_count.store(0);

    future<int> f4 = dataflow(exec,
        &future_int_f2
      , dataflow(exec, &future_int_f1, make_ready_future())
      , dataflow(exec, &future_int_f1, make_ready_future())
    );

    HPX_TEST_EQ(f4.get(), 2);
    HPX_TEST_EQ(future_int_f1_count, 2u);
    HPX_TEST_EQ(future_int_f2_count, 1u);
    future_int_f1_count.store(0);
    future_int_f2_count.store(0);

    future_int_f_vector_count.store(0);
    std::vector<future<int> > vf;
    for(std::size_t i = 0; i < 10; ++i)
    {
        vf.push_back(dataflow(exec, &future_int_f1, make_ready_future()));
    }
    future<int> f5 = dataflow(exec, &future_int_f_vector, std::ref(vf));

    HPX_TEST_EQ(f5.get(), 10);
}
开发者ID:ShmuelLevine,项目名称:hpx,代码行数:64,代码来源:local_dataflow_executor_v1.cpp


示例18: unlock

		void unlock() {
			locked.store(false, std::memory_order_release);
		}
开发者ID:davidklaftenegger,项目名称:qd_library,代码行数:3,代码来源:tatas_lock.hpp


示例19: operator

 void operator()(BlockingQueue<int> &queue) {
   for (int i = 0; i < size; ++i) {
     queue.WaitAndPush(product_item.fetch_add(1));
   }
 }
开发者ID:haitaoy,项目名称:thread_pool_service,代码行数:5,代码来源:blocking_queue_test.cpp


示例20: bool

 inline operator bool() const
 {
     return m_value.load();
 }
开发者ID:cas4ey,项目名称:signals_library,代码行数:4,代码来源:mutex.hpp



注:本文中的std::atomic类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ std::atomic_bool类代码示例发布时间:2022-05-31
下一篇:
C++ std::array类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap