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


C++ condition_variable::wait方法代码示例

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


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

示例1: execute

 void execute() {
     while (!requires_stop_) {
         std::function<void(void)> function;
         {
             std::unique_lock<std::mutex> lock(works_mutex_);
             if (works_.empty()) {
                 workable_.wait(lock);
             }
             function = works_.front();
             works_.pop_front();
         }
         // MEMO: Do not catch an exception of async.
         function();
     }
 }
开发者ID:takayoshiotake,项目名称:SerialDispatcher_Cpp,代码行数:15,代码来源:serial_dispatcher.hpp

示例2: l

std::pair<size_t, ExternCompiler*> CompilerPool::getCompiler() {
  std::unique_lock<std::mutex> l(m_compilerLock);

  m_compilerCv.wait(l, [&] {
    return m_freeCount.load(std::memory_order_relaxed) != 0;
  });
  m_freeCount -= 1;

  for (size_t id = 0; id < m_compilers.size(); ++id) {
    auto ret = m_compilers.exchange(id, nullptr);
    if (ret) return std::make_pair(id, ret);
  }

  not_reached();
}
开发者ID:swtaarrs,项目名称:hhvm,代码行数:15,代码来源:extern-compiler.cpp

示例3: worker_2

void worker_2() {
    for (int i = 0; i < 8; i += 1) {
        std::unique_lock<std::mutex> lock(mtx);
        condition.wait(lock, [=]() -> bool { return produced; });

        auto consumer = [=]() {
            produced = false;
            consumed = true;
            std::cout << "consuming " << i << std::endl << std::flush;
        };
        consumer();

        condition.notify_one();
    }
}
开发者ID:BossKwei,项目名称:temp,代码行数:15,代码来源:mutex_1.cpp

示例4: Run

 /** Thread function */
 void Run()
 {
     while (true) {
         std::unique_ptr<WorkItem> i;
         {
             std::unique_lock<std::mutex> lock(cs);
             while (running && queue.empty())
                 cond.wait(lock);
             if (!running)
                 break;
             i = std::move(queue.front());
             queue.pop_front();
         }
         (*i)();
     }
 }
开发者ID:litecoin-project,项目名称:litecoin,代码行数:17,代码来源:httpserver.cpp

示例5: produce

void produce()
{
  for (auto i = 0u; i < 2 * BUFFER_SIZE; ++i) {
    std::unique_lock<std::mutex> locker(mu);
    full.wait(locker, [] {return vec.size() < BUFFER_SIZE;});
    auto was_empty = vec.empty();
    vec.push_back(i);
    locker.unlock();

    if (was_empty) {
      empty.notify_one();
    }

    std::this_thread::sleep_for(slp);
  }
}
开发者ID:CCJY,项目名称:coliru,代码行数:16,代码来源:main.cpp

示例6: async

std::future<typename std::result_of<Func(Args...)>::type> StartJob(Func func, Args... args) {

	// wait until the thread count drops below the maximum
	std::unique_lock<std::mutex> lock(g_threadcount_mutex);
	while(g_threadcount >= g_threadcount_max) {
		g_threadcount_cv.wait(lock);
	}

	// increment the thread count
	++g_threadcount;

	// start the thread
	return std::async(std::launch::async, JobWrapper<Func, Args...>,
					  func, std::forward<Args>(args)...);

}
开发者ID:ChuyuHsu,项目名称:2048-ai-emscripten,代码行数:16,代码来源:PlayTests.cpp

示例7: thread_fn

                void thread_fn()
                {
					while (enabled)
					{
						std::unique_lock<std::mutex> locker(mutex); 
						cv.wait(locker, [&](){ return !fqueue.empty() || !enabled; });
						while(!fqueue.empty())
						{
							fn_type fn = fqueue.front(); 
							fqueue.pop();
							locker.unlock();
							fn();
							locker.lock();
						}                              
					}
                }
开发者ID:Yashchuk,项目名称:diplom-1,代码行数:16,代码来源:threadPool.cpp

示例8: wait

 void wait() {
     std::unique_lock<std::mutex> lk(mtx);
     ++wait_count;
     if(wait_count != target_wait_count) {
         // not all threads have arrived yet; go to sleep until they do
         cond_var.wait(lk, 
             [this]() { return wait_count == target_wait_count; });
     } else {
         // we are the last thread to arrive; wake the others and go on
         cond_var.notify_all();
     }
     // note that if you want to reuse the barrier, you will have to
     // reset wait_count to 0 now before calling wait again
     // if you do this, be aware that the reset must be synchronized with
     // threads that are still stuck in the wait
 }
开发者ID:jon-engelbert,项目名称:concurrent-solutions,代码行数:16,代码来源:reusable_barrier_custom_class.cpp

示例9: bar2

void bar2()
{
	//Acquire the lock
	std::unique_lock<std::mutex> lck(m);

	//Wait until the first thread is done, so that this may go
	cv.wait(lck);

	//Random task that this thread is doing
	for (int i = 100; i > 0; --i)
	{
		printf("Random Other Tasking: %d\n", i);
	}

	printf("Finally ready!\n");
}
开发者ID:IGME-RIT,项目名称:core-multithreadingIssues,代码行数:16,代码来源:ConditionVariables.cpp

示例10: MergeWorkerThreadStats

void MergeWorkerThreadStats() {
    std::unique_lock<std::mutex> lock(workListMutex);
    std::unique_lock<std::mutex> doneLock(reportDoneMutex);
    // Set up state so that the worker threads will know that we would like
    // them to report their thread-specific stats when they wake up.
    reportWorkerStats = true;
    reporterCount = threads.size();

    // Wake up the worker threads.
    workListCondition.notify_all();

    // Wait for all of them to merge their stats.
    reportDoneCondition.wait(lock, []() { return reporterCount == 0; });

    reportWorkerStats = false;
}
开发者ID:Jerry-King,项目名称:pbrt-v3,代码行数:16,代码来源:parallel.cpp

示例11: runtime_error

int
main(int argc, char **argv)
{
    auto params = parseArgs(argc, argv);

    // TODO: remove with GnuTLS >= 3.3
    int rc = gnutls_global_init();
    if (rc != GNUTLS_E_SUCCESS)
        throw std::runtime_error(std::string("Error initializing GnuTLS: ")+gnutls_strerror(rc));

    auto ca_tmp = dht::crypto::generateIdentity("DHT Node CA");
    auto crt_tmp = dht::crypto::generateIdentity("Scanner node", ca_tmp);

    DhtRunner dht;
    dht.run(params.port, crt_tmp, true, params.network);

    if (not params.bootstrap.first.empty())
        dht.bootstrap(params.bootstrap.first.c_str(), params.bootstrap.second.c_str());

    std::cout << "OpenDht node " << dht.getNodeId() << " running on port " <<  params.port << std::endl;
    std::cout << "Scanning network..." << std::endl;
    auto all_nodes = std::make_shared<NodeSet>();

    dht::InfoHash cur_h {};
    cur_h.setBit(8*HASH_LEN-1, 1);

    std::this_thread::sleep_for(std::chrono::seconds(2));

    std::atomic_uint done {false};
    step(dht, done, all_nodes, cur_h, 0);

    {
        std::mutex m;
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, [&](){
            return done.load() == 0;
        });
    }

    std::cout << std::endl << "Scan ended: " << all_nodes->size() << " nodes found." << std::endl;
    for (const auto& n : *all_nodes)
        std::cout << "Node " << *n << std::endl;

    dht.join();
    gnutls_global_deinit();
    return 0;
}
开发者ID:Andrew-Klaas,项目名称:opendht,代码行数:47,代码来源:dhtscanner.cpp

示例12: wait

	bool wait()
	{
          std::unique_lock<std::mutex> lock(m_mutex);
          unsigned int gen = m_generation;

          if (--m_count == 0)
          {
            m_generation++;
            m_count = m_threshold;
            m_cond.notify_all();
            return true;
          }

          while (gen == m_generation)
            m_cond.wait(lock);
          return false;
	}
开发者ID:igfuw,项目名称:libcloudphxx,代码行数:17,代码来源:multi_gpu_utils.hpp

示例13: get

			T get()
			{
				T front;

				{
					auto_lock lock(mutex_);
					while(queue_.empty())
						not_empty_.wait(mutex_, std::chrono::milliseconds(INFINITE));

					assert(!queue_.empty());
					front = std::move(queue_.front());
					queue_.pop_front();
				}

				not_full_.notify_one();
				return front;
			}
开发者ID:Crawping,项目名称:iocpframework,代码行数:17,代码来源:bounded_block_queue.hpp

示例14: fakeSocketConnect

int fakeSocketConnect(int fd1, int fd2)
{
    std::vector<FakeSocketPair>& fds = getFds();
    std::unique_lock<std::mutex> lock(theMutex);
    if (fd1 < 0 || fd2 < 0 || static_cast<unsigned>(fd1/2) >= fds.size() || static_cast<unsigned>(fd2/2) >= fds.size())
    {
        loggingBuffer << "FakeSocket EBADF: Connect #" << fd1 << " to #" << fd2 << flush();
        errno = EBADF;
        return -1;
    }
    if (fd1/2 == fd2/2)
    {
        loggingBuffer << "FakeSocket EBADF: Connect #" << fd1 << " to #" << fd2 << flush();
        errno = EBADF;
        return -1;
    }

    FakeSocketPair& pair1 = fds[fd1/2];
    FakeSocketPair& pair2 = fds[fd2/2];

    if ((fd1&1) || (fd2&1))
    {
        loggingBuffer << "FakeSocket EISCONN: Connect #" << fd1 << " to #" << fd2 << flush();
        errno = EISCONN;
        return -1;
    }

    if (!pair2.listening || pair2.connectingFd != -1)
    {
        loggingBuffer << "FakeSocket ECONNREFUSED: Connect #" << fd1 << " to #" << fd2 << flush();
        errno = ECONNREFUSED;
        return -1;
    }

    pair2.connectingFd = fd1;
    theCV.notify_all();

    while (pair1.fd[1] == -1)
        theCV.wait(lock);

    assert(pair1.fd[1] == pair1.fd[0] + 1);

    loggingBuffer << "FakeSocket Connect #" << fd1 << " to #" << fd2 << ": #" << pair1.fd[1] << flush();

    return 0;
}
开发者ID:LibreOffice,项目名称:online,代码行数:46,代码来源:FakeSocket.cpp

示例15: run

	void run(processing_function func) {
		proc = func;

		srand(time(NULL));

		const int concurrency_limit = 1;

		while(1) {
			while(running_requests < concurrency_limit) {
				++running_requests;
				queue_peek(client, next_request_id++, request_size);
				//fprintf(stderr, "%d running_requests\n", (int)running_requests);
			}
			std::unique_lock<std::mutex> lock(mutex);
			condition.wait(lock, [this]{return running_requests < concurrency_limit;});
		}
	}
开发者ID:euroelessar,项目名称:grape,代码行数:17,代码来源:queue-pump.cpp


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