当前位置: 首页>>代码示例>>C++>>正文


C++ atomic::compare_exchange_strong方法代码示例

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


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

示例1: try_lock

 bool try_lock() {
   size_t bad_id = -1;
   auto ThisID = _hash(std::this_thread::get_id());
   if (!_lock.compare_exchange_strong(bad_id, ThisID) && !(_lock.compare_exchange_strong(ThisID, ThisID))) {
     return false;
   }
   ++_lock_count;
   return true;
 }
开发者ID:dallasrobotics,项目名称:xtl,代码行数:9,代码来源:recursive_spin_lock.hpp

示例2: mark_for_deletion

	   /**
	    * Try mark the file for deletion. Only few file states permit this operation to happen.
	    *
        * @return true if file was marked for deletion
        * No one should reference this file since it is marked for deletion
	    */
	   inline bool mark_for_deletion(){
		   boost::mutex::scoped_lock lock(m_state_changed_mux);

		   bool marked = false;

		   LOG (INFO) << "Managed file OTO \"" << fqp() << "\" with state \"" << state() << "\" is requested for deletion." <<
				   "subscribers # = " <<  m_subscribers.load(std::memory_order_acquire) << "\n";
		   // check all states that allow to mark the file for deletion:
		   State expected = State::FILE_IS_IDLE;

		   // look for "idle marker"
           marked = m_state.compare_exchange_strong(expected, State::FILE_IS_MARKED_FOR_DELETION);

           if(marked){
        	   // wait for all detaching clients to finish:
        	   boost::unique_lock<boost::mutex> detaching_lock(m_detaching_mux_guard);
        	   m_detaching_condition.wait(detaching_lock, [&]{ return (m_detaching_clients.size() == 0); });
        	   detaching_lock.unlock();

        	   // go ahead, no detaching clients are in progress more
        	   m_state_changed_condition.notify_all();
        	   LOG (INFO) << "Managed file OTO \"" << fqp() << "\" with state \"" << state() <<
        			   "\" is successfully marked for deletion." << "\n";
        	   if(m_subscribers.load(std::memory_order_acquire) == 0)
        		   return true;
        	   return false;
           }

           expected = State::FILE_IS_FORBIDDEN;
           marked   =  m_state.compare_exchange_strong(expected, State::FILE_IS_MARKED_FOR_DELETION);

           if(marked){
        	   m_state_changed_condition.notify_all();
        	   LOG (INFO) << "Managed file OTO \"" << fqp() << "\" with state \"" << state() <<
        			   "\" is successfully marked for deletion." << "\n";
        	   if(m_subscribers.load(std::memory_order_acquire) == 0)
        		   return true;
        	   return false;
           }

           expected = State::FILE_IS_AMORPHOUS;
           marked   =  m_state.compare_exchange_strong(expected, State::FILE_IS_MARKED_FOR_DELETION);

           m_state_changed_condition.notify_all();
           marked = (marked && (m_subscribers.load(std::memory_order_acquire) == 0));
           std::string marked_str = marked ? "successfully" : "NOT";
    	   LOG (INFO) << "Managed file OTO \"" << fqp() << "\" with state \"" << state() <<
    			   "\" is " << marked_str  << " marked for deletion." << "\n";

    	   return marked;
	   }
开发者ID:ImpalaToGo,项目名称:ImpalaToGo,代码行数:57,代码来源:managed-file.hpp

示例3: s_execute

    bool s_execute(WFVector *vec, void *&v){
        ArrayElement *spot=vec->getSpot(pos);
        
        CasHelper *cah=new CasHelper(this); 

        void *ahelper=assoc.load();
        while ( ahelper == NULL){
            void *cvalue=spot->load(std::memory_order_relaxed);

            if (Helper::isHelper(cvalue)){
                Helper *tHelper=Helper::unmark(cvalue);
                if (tHelper->watch(cvalue, spot)){
                    Helper::remove(vec, pos, cvalue);
                    tHelper->unwatch();
                }
                ahelper=assoc.load();
                continue;
            }

            else if (cvalue == o_value){   
                
                void *tempMarked=Helper::mark(cah);
                if (spot->compare_exchange_strong(cvalue,tempMarked )){
                    if (assoc.compare_exchange_strong(ahelper, tempMarked) || ahelper == tempMarked){
                        spot->compare_exchange_strong(tempMarked, n_value);
                    }
                    else{
                        spot->compare_exchange_strong(tempMarked, o_value);
                        cah->safeFree();
                    }
                    break;
                }
                
            }
            else{
                assoc.compare_exchange_strong(ahelper, cvalue);
                cah->unsafeFree();
                break;
            }
        }//End while

        ahelper=assoc.load();
        if (Helper::isHelper(ahelper)){
            return true;
        }
        else{
            v=ahelper;
            return false;
        }

    }
开发者ID:ucf-cs,项目名称:Tervel,代码行数:51,代码来源:wfv_classes.hpp

示例4: main

int main()
{
    ai= 3;
    valsout();
    cout << "hello world" << endl;
 
    // tst_val != ai   ==>  tst_val is modified
    exchanged= ai.compare_exchange_strong( tst_val, new_val );
    valsout();
 
    // tst_val == ai   ==>  ai is modified
    exchanged= ai.compare_exchange_strong( tst_val, new_val );
    valsout();
 
    return 0;
}
开发者ID:CCJY,项目名称:coliru,代码行数:16,代码来源:main.cpp

示例5: thread_2

void thread_2()
{
    int expected=1;
    while (!flag.compare_exchange_strong(expected, 2, std::memory_order_acq_rel)) {
        expected = 1;
    }
}
开发者ID:CCJY,项目名称:coliru,代码行数:7,代码来源:main.cpp

示例6: unlock

 void unlock ()
 {
     bool expected = true;
     POMAGMA_ASSERT(m_flag.compare_exchange_strong(expected, false),
             "unlock contention");
     store_barrier();
 }
开发者ID:imclab,项目名称:pomagma,代码行数:7,代码来源:threading.hpp

示例7: lock

 void lock() {
     Node::Ptr unlocked(nullptr, 0);
     if (!tail_.compare_exchange_strong(unlocked, Node::Ptr(nullptr, 1),
                                        std::memory_order_acquire)) {
         slowpathLock(unlocked);
     }
 }
开发者ID:msullivan,项目名称:rmc-compiler,代码行数:7,代码来源:qspinlock_c11.hpp

示例8: pop

 std::shared_ptr<T> pop()
 {
     std::atomic<void*>& hp = get_hazard_pointer_for_current_thread();
     node* old_head = head.load();
     do {
         node* temp;
         do { // loop until you've set the harzard pointer to head
             temp = old_head;
             hp.store(old_head);
             old_head = head.load();
         } while (old_head != temp);
     }
     while (old_head && 
            !head.compare_exchange_strong(old_head, old_head->next));
     hp.store(nullptr); // clear hazard pointer once you're finished
     std::shared_ptr<T> res;
     if (old_head) {
         res.swap(old_head->data);
         if (outstanding_hazard_pointers_for(old_head)) { 
             // check for hazard pointers referencing
             // a node before you delete it
             reclaim_later(old_head);
         }
         else {
             delete old_head;
         }
         delete_nodes_with_no_hazards();
     }
     return res;
 }
开发者ID:subjam,项目名称:concurrency-in-action,代码行数:30,代码来源:stack_hp.cpp

示例9: lock

 void lock ()
 {
     load_barrier();
     bool expected = false;
     POMAGMA_ASSERT(m_flag.compare_exchange_strong(expected, true),
             "lock contention");
 }
开发者ID:imclab,项目名称:pomagma,代码行数:7,代码来源:threading.hpp

示例10: Pop

  int Pop()
  {
      while (count.load(std::memory_order_acquire) > 1)
      {
          int head1 = head.load(std::memory_order_acquire);
          int next1 = array[head1].Next.exchange(-1, std::memory_order_seq_cst);

          if (next1 >= 0)
          {
              int head2 = head1;
              if (head.compare_exchange_strong(head2, next1, std::memory_order_seq_cst))
              {
                  count.fetch_sub(1, std::memory_order_seq_cst);
                  return head1;
              }
              else
              {
                  array[head1].Next.exchange(next1, std::memory_order_seq_cst);
              }
          }
          else
          {
            sched_yield();
          }
      }

      return -1;
  }
开发者ID:hityangzhen,项目名称:sctbenchmarks,代码行数:28,代码来源:SafeStack.cpp

示例11: malloc

JNIEXPORT void JNICALL Java_JNITest_print0
  (JNIEnv * jenv, jobject jobj, jstring jstr) {

      struct Malloc* defMalloc = defaultMalloc.load();
    //   if (defaultMalloc == nullptr) {
          std::cout << "lookup... " << std::endl;
          jclass klass = jenv->GetObjectClass(jobj);
          jmethodID mid = jenv->GetMethodID(klass, "multiply", "(JI)J");

          struct Malloc* nullObj = nullptr;

          jclass globalClass = reinterpret_cast<jclass>(jenv->NewGlobalRef(klass));
          jobject globalObj = reinterpret_cast<jobject>(jenv->NewGlobalRef(jobj));

          defMalloc = (struct Malloc*) malloc(sizeof(struct Malloc));
          defMalloc->mallocClass = globalClass;
          defMalloc->mallocObj = globalObj;
          defMalloc->mallocMethodId = mid;

          if (!defaultMalloc.compare_exchange_strong(nullObj, defMalloc)) {
              free(defMalloc);
              jenv->DeleteGlobalRef(globalObj);
              jenv->DeleteGlobalRef(globalClass);
              std::cout << "ERROR" << std::endl;
              return;
          }
    //   }

      jlong address = jenv->CallLongMethod(defMalloc->mallocObj, defMalloc->mallocMethodId, 123, 10);
      std::cout << "hello" << ": " << address << std::endl;
  }
开发者ID:mdogan,项目名称:test,代码行数:31,代码来源:JNITest.cpp

示例12: synchronize_rcu

 void synchronize_rcu() noexcept {
     const uint64_t waitForVersion = updaterVersion.load()+1;
     auto tmp = waitForVersion-1;
     updaterVersion.compare_exchange_strong(tmp, waitForVersion);
     for (int i=0; i < maxThreads; i++) {
         while (readersVersion[i*CLPAD].load() < waitForVersion) { } // spin
     }
 }
开发者ID:pramalhe,项目名称:ConcurrencyFreaks,代码行数:8,代码来源:URCUGraceVersion.hpp

示例13: tryCollect

bool Participant::tryCollect() {
    remote_thread_fence::trigger();

    uintptr_t cur_epoch = epoch_.load(mo_rlx);

    // Check whether all active threads are in the current epoch so we
    // can advance it.
    // As we do it, we lazily clean up exited threads.
try_again:
    std::atomic<Participant::Ptr> *prevp = &participants_;
    Participant::Ptr cur = prevp->load(mo_acq);
    while (cur) {
        Participant::Ptr next = cur->next_.load(mo_rlx);
        if (next.tag()) {
            // This node has exited. Try to unlink it from the
            // list. This will fail if it's already been unlinked or
            // the previous node has exited; in those cases, we start
            // back over at the head of the list.
            next = Ptr(next, 0); // clear next's tag
            if (prevp->compare_exchange_strong(cur, next, mo_rlx)) {
                Guard g(this);
                g.unlinked(cur.ptr());
            } else {
                goto try_again;
            }
        } else {
            // We can only advance the epoch if every thread in a critical
            // section is in the current epoch.
            if (cur->in_critical_.load(mo_rlx) &&
                cur->epoch_.load(mo_rlx) != cur_epoch) {
                return false;
            }
            prevp = &cur->next_;
        }

        cur = next;
    }

    // Everything visible to the reads from the loop we want hb before
    // the epoch update.
    std::atomic_thread_fence(mo_acq);
    // Try to advance the global epoch
    uintptr_t new_epoch = cur_epoch + 1;
    if (!global_epoch_.compare_exchange_strong(cur_epoch, new_epoch,
                                               mo_acq_rel)) {
        return false;
    }

    // Garbage collect
    global_garbage_[(new_epoch+1) % kNumEpochs].collect();
    garbage_.collect();
    // Now that the collection is done, we can safely update our
    // local epoch.
    epoch_ = new_epoch;

    return true;
}
开发者ID:msullivan,项目名称:rmc-compiler,代码行数:57,代码来源:epoch_c11simp.cpp

示例14: lock

    void lock() noexcept {
        std::int32_t collisions = 0, tests = 0, expected = 0;
        // after max. spins or collisions suspend via futex
        while ( BOOST_FIBERS_SPIN_MAX_TESTS > tests && BOOST_FIBERS_SPIN_MAX_COLLISIONS > collisions) {
            // avoid using multiple pause instructions for a delay of a specific cycle count
            // the delay of cpu_relax() (pause on Intel) depends on the processor family
            // the cycle count can not guaranteed from one system to the next
            // -> check the shared variable 'value_' in between each cpu_relax() to prevent
            //    unnecessarily long delays on some systems
            // test shared variable 'status_'
            // first access to 'value_' -> chache miss
            // sucessive acccess to 'value_' -> cache hit
            // if 'value_' was released by other fiber
            // cached 'value_' is invalidated -> cache miss
            if ( 0 != ( expected = value_.load( std::memory_order_relaxed) ) ) {
                ++tests;
#if !defined(BOOST_FIBERS_SPIN_SINGLE_CORE)
                // give CPU a hint that this thread is in a "spin-wait" loop
                // delays the next instruction's execution for a finite period of time (depends on processor family)
                // the CPU is not under demand, parts of the pipeline are no longer being used
                // -> reduces the power consumed by the CPU
                // -> prevent pipeline stalls
                cpu_relax();
#else
                // std::this_thread::yield() allows this_thread to give up the remaining part of its time slice,
                // but only to another thread on the same processor
                // instead of constant checking, a thread only checks if no other useful work is pending
                std::this_thread::yield();
#endif
            } else if ( ! value_.compare_exchange_strong( expected, 1, std::memory_order_acquire, std::memory_order_release) ) {
                // spinlock now contended
                // utilize 'Binary Exponential Backoff' algorithm
                // linear_congruential_engine is a random number engine based on Linear congruential generator (LCG)
                static thread_local std::minstd_rand generator;
                static std::uniform_int_distribution< std::int32_t > distribution{ 0, static_cast< std::int32_t >( 1) << collisions };
                const std::int32_t z = distribution( generator);
                ++collisions;
                for ( std::int32_t i = 0; i < z; ++i) {
                    // -> reduces the power consumed by the CPU
                    // -> prevent pipeline stalls
                    cpu_relax();
                }
            } else {
                // success, lock acquired
                return;
            }
        }
        // failure, lock not acquired
        // pause via futex
        if ( 2 != expected) {
            expected = value_.exchange( 2, std::memory_order_acquire);
        }
        while ( 0 != expected) {
            futex_wait( & value_, 2);
            expected = value_.exchange( 2, std::memory_order_acquire);
        }
    }
开发者ID:3Jade,项目名称:Sprawl,代码行数:57,代码来源:spinlock_ttas_futex.hpp

示例15: increase_external_count

	static void increase_external_count(std::atomic<counted_node_ptr> &counter, counted_node_ptr &old_counter) {
		counted_node_ptr new_counter;
		do {
			new_counter = old_counter;
			new_counter.inc();
		} while (!counter.compare_exchange_strong(old_counter, new_counter, std::memory_order_acquire, std::memory_order_relaxed));

		old_counter.set_counter(new_counter.get_counter());
	}
开发者ID:ssteinberg,项目名称:ste,代码行数:9,代码来源:concurrent_queue.hpp


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