Skip site navigation (1)Skip section navigation (2)

FreeBSD Manual Pages

  
 
  

home | help
std::this_thread::yield(3)    C++ Standard Libary   std::this_thread::yield(3)

NAME
       std::this_thread::yield - std::this_thread::yield

Synopsis
	  Defined in header <thread>
	  void yield() noexcept;      (since C++11)

	  Provides a hint to the implementation	to reschedule the execution of
       threads,
	  allowing other threads to run.

Parameters
	  (none)

Return value
	  (none)

Notes
	  The  exact  behavior of this function	depends	on the implementation,
       in particular on
	  the mechanics	of the OS scheduler in use and the state of  the  sys-
       tem. For	example, a
	  first-in-first-out  realtime	scheduler  (SCHED_FIFO in Linux) would
       suspend the
	  current thread and put it on the back	of the queue of	the  same-pri-
       ority threads that
	  are ready to run (and	if there are no	other threads at the same pri-
       ority, yield has
	  no effect).

Example
       // Run this code

	#include <iostream>
	#include <chrono>
	#include <thread>

	// "busy sleep"	while suggesting that other threads run
	// for a small amount of time
	void little_sleep(std::chrono::microseconds us)
	{
	    auto start = std::chrono::high_resolution_clock::now();
	    auto end = start + us;
	    do {
		std::this_thread::yield();
	    } while (std::chrono::high_resolution_clock::now() < end);
	}

	int main()
	{
	    auto start = std::chrono::high_resolution_clock::now();

	    little_sleep(std::chrono::microseconds(100));

	    auto elapsed = std::chrono::high_resolution_clock::now() - start;
	    std::cout << "waited for "
		      <<     std::chrono::duration_cast<std::chrono::microsec-
       onds>(elapsed).count()
		      << " microseconds\n";
	}

Possible output:
	waited for 128 microseconds

See also
http://cppreference.com		  2022.07.31	    std::this_thread::yield(3)

Want to link to this manual page? Use this URL:
<https://man.freebsd.org/cgi/man.cgi?query=std::this_thread::yield&sektion=3&manpath=FreeBSD+Ports+15.0>

home | help