thread_ref.qbk
来自「Boost provides free peer-reviewed portab」· QBK 代码 · 共 1,065 行 · 第 1/2 页
QBK
1,065 行
[/ (C) Copyright 2007-8 Anthony Williams. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).][section:thread_management Thread Management][heading Synopsis]The __thread__ class is responsible for launching and managing threads. Each __thread__ object represents a single thread of execution,or __not_a_thread__, and at most one __thread__ object represents a given thread of execution: objects of type __thread__ are notcopyable.Objects of type __thread__ are movable, however, so they can be stored in move-aware containers, and returned from functions. Thisallows the details of thread creation to be wrapped in a function. boost::thread make_thread(); void f() { boost::thread some_thread=make_thread(); some_thread.join(); }[Note: On compilers that support rvalue references, __thread__ provides a proper move constructor and move-assignment operator, andtherefore meets the C++0x ['MoveConstructible] and ['MoveAssignable] concepts. With such compilers, __thread__ can therefore be usedwith containers that support those concepts.For other compilers, move support is provided with a move emulation layer, so containers must explicitly detect that move emulationlayer. See <boost/thread/detail/move.hpp> for details.][heading Launching threads]A new thread is launched by passing an object of a callable type that can be invoked with no parameters to the constructor. Theobject is then copied into internal storage, and invoked on the newly-created thread of execution. If the object must not (orcannot) be copied, then `boost::ref` can be used to pass in a reference to the function object. In this case, the user of__boost_thread__ must ensure that the referred-to object outlives the newly-created thread of execution. struct callable { void operator()(); }; boost::thread copies_are_safe() { callable x; return boost::thread(x); } // x is destroyed, but the newly-created thread has a copy, so this is OK boost::thread oops() { callable x; return boost::thread(boost::ref(x)); } // x is destroyed, but the newly-created thread still has a reference // this leads to undefined behaviourIf you wish to construct an instance of __thread__ with a function or callable object that requires arguments to be supplied,this can be done by passing additional arguments to the __thread__ constructor: void find_the_question(int the_answer); boost::thread deep_thought_2(find_the_question,42);The arguments are ['copied] into the internal thread structure: if a reference is required, use `boost::ref`, just as for referencesto callable functions.There is an unspecified limit on the number of additional arguments that can be passed.[heading Exceptions in thread functions]If the function or callable object passed to the __thread__ constructor propagates an exception when invoked that is not of type__thread_interrupted__, `std::terminate()` is called. [heading Joining and detaching]When the __thread__ object that represents a thread of execution is destroyed the thread becomes ['detached]. Once a thread isdetached, it will continue executing until the invocation of the function or callable object supplied on construction has completed,or the program is terminated. A thread can also be detached by explicitly invoking the __detach__ member function on the __thread__object. In this case, the __thread__ object ceases to represent the now-detached thread, and instead represents __not_a_thread__.In order to wait for a thread of execution to finish, the __join__ or __timed_join__ member functions of the __thread__ object must beused. __join__ will block the calling thread until the thread represented by the __thread__ object has completed. If the thread ofexecution represented by the __thread__ object has already completed, or the __thread__ object represents __not_a_thread__, then __join__returns immediately. __timed_join__ is similar, except that a call to __timed_join__ will also return if the thread being waited fordoes not complete when the specified time has elapsed.[heading Interruption]A running thread can be ['interrupted] by invoking the __interrupt__ member function of the corresponding __thread__ object. When theinterrupted thread next executes one of the specified __interruption_points__ (or if it is currently __blocked__ whilst executing one)with interruption enabled, then a __thread_interrupted__ exception will be thrown in the interrupted thread. If not caught,this will cause the execution of the interrupted thread to terminate. As with any other exception, the stack will be unwound, anddestructors for objects of automatic storage duration will be executed.If a thread wishes to avoid being interrupted, it can create an instance of __disable_interruption__. Objects of this class disableinterruption for the thread that created them on construction, and restore the interruption state to whatever it was before ondestruction: void f() { // interruption enabled here { boost::this_thread::disable_interruption di; // interruption disabled { boost::this_thread::disable_interruption di2; // interruption still disabled } // di2 destroyed, interruption state restored // interruption still disabled } // di destroyed, interruption state restored // interruption now enabled }The effects of an instance of __disable_interruption__ can be temporarily reversed by constructing an instance of__restore_interruption__, passing in the __disable_interruption__ object in question. This willrestore the interruption state to what it was when the __disable_interruption__ object was constructed, and thendisable interruption again when the __restore_interruption__ object is destroyed. void g() { // interruption enabled here { boost::this_thread::disable_interruption di; // interruption disabled { boost::this_thread::restore_interruption ri(di); // interruption now enabled } // ri destroyed, interruption disable again } // di destroyed, interruption state restored // interruption now enabled }At any point, the interruption state for the current thread can be queried by calling __interruption_enabled__.[#interruption_points][heading Predefined Interruption Points]The following functions are ['interruption points], which will throw __thread_interrupted__ if interruption is enabled for thecurrent thread, and interruption is requested for the current thread:* [join_link `boost::thread::join()`]* [timed_join_link `boost::thread::timed_join()`]* [cond_wait_link `boost::condition_variable::wait()`]* [cond_timed_wait_link `boost::condition_variable::timed_wait()`]* [cond_any_wait_link `boost::condition_variable_any::wait()`]* [cond_any_timed_wait_link `boost::condition_variable_any::timed_wait()`]* [link thread.thread_management.thread.sleep `boost::thread::sleep()`]* __sleep__* __interruption_point__[heading Thread IDs]Objects of class __thread_id__ can be used to identify threads. Each running thread of execution has a unique ID obtainablefrom the corresponding __thread__ by calling the `get_id()` member function, or by calling `boost::this_thread::get_id()` fromwithin the thread. Objects of class __thread_id__ can be copied, and used as keys in associative containers: the full range ofcomparison operators is provided. Thread IDs can also be written to an output stream using the stream insertion operator, though theoutput format is unspecified.Each instance of __thread_id__ either refers to some thread, or __not_a_thread__. Instances that refer to __not_a_thread__compare equal to each other, but not equal to any instances that refer to an actual thread of execution. The comparison operators on__thread_id__ yield a total order for every non-equal thread ID.[section:thread Class `thread`] #include <boost/thread/thread.hpp> class thread { public: thread(); ~thread(); template <class F> explicit thread(F f); template <class F,class A1,class A2,...> thread(F f,A1 a1,A2 a2,...); template <class F> thread(detail::thread_move_t<F> f); // move support thread(detail::thread_move_t<thread> x); thread& operator=(detail::thread_move_t<thread> x); operator detail::thread_move_t<thread>(); detail::thread_move_t<thread> move(); void swap(thread& x); class id; id get_id() const; bool joinable() const; void join(); bool timed_join(const system_time& wait_until); template<typename TimeDuration> bool timed_join(TimeDuration const& rel_time); void detach(); static unsigned hardware_concurrency(); typedef platform-specific-type native_handle_type; native_handle_type native_handle(); void interrupt(); bool interruption_requested() const; // backwards compatibility bool operator==(const thread& other) const; bool operator!=(const thread& other) const; static void yield(); static void sleep(const system_time& xt); }; void swap(thread& lhs,thread& rhs);[section:default_constructor Default Constructor] thread();[variablelist[[Effects:] [Constructs a __thread__ instance that refers to __not_a_thread__.]][[Throws:] [Nothing]]][endsect][section:callable_constructor Thread Constructor] template<typename Callable> thread(Callable func);[variablelist[[Preconditions:] [`Callable` must by copyable.]][[Effects:] [`func` is copied into storage managed internally by the thread library, and that copy is invoked on a newly-createdthread of execution. If this invocation results in an exception being propagated into the internals of the thread library that isnot of type __thread_interrupted__, then `std::terminate()` will be called.]][[Postconditions:] [`*this` refers to the newly created thread of execution.]][[Throws:] [__thread_resource_error__ if an error occurs.]]][endsect][section:multiple_argument_constructor Thread Constructor with arguments] template <class F,class A1,class A2,...> thread(F f,A1 a1,A2 a2,...);[variablelist[[Preconditions:] [`F` and each `A`n must by copyable or movable.]][[Effects:] [As if [linkthread.thread_management.thread.callable_constructor`thread(boost::bind(f,a1,a2,...))`. Consequently, `f` and each `a`nare copied into internal storage for access by the new thread.]]][[Postconditions:] [`*this` refers to the newly created thread of execution.]][[Throws:] [__thread_resource_error__ if an error occurs.]][[Note:] [Currently up to nine additional arguments `a1` to `a9` can be specified in addition to the function `f`.]]][endsect][section:destructor Thread Destructor] ~thread();[variablelist[[Effects:] [If `*this` has an associated thread of execution, calls __detach__. Destroys `*this`.]][[Throws:] [Nothing.]]][endsect][section:joinable Member function `joinable()`] bool joinable() const;[variablelist[[Returns:] [`true` if `*this` refers to a thread of execution, `false` otherwise.]][[Throws:] [Nothing]]][endsect][section:join Member function `join()`] void join();[variablelist[[Preconditions:] [`this->get_id()!=boost::this_thread::get_id()`]][[Effects:] [If `*this` refers to a thread of execution, waits for that thread of execution to complete.]][[Postconditions:] [If `*this` refers to a thread of execution on entry, that thread of execution has completed. `*this` no longer refers to any thread of execution.]][[Throws:] [__thread_interrupted__ if the current thread of execution is interrupted.]][[Notes:] [`join()` is one of the predefined __interruption_points__.]]][endsect][section:timed_join Member function `timed_join()`] bool timed_join(const system_time& wait_until); template<typename TimeDuration> bool timed_join(TimeDuration const& rel_time);[variablelist[[Preconditions:] [`this->get_id()!=boost::this_thread::get_id()`]][[Effects:] [If `*this` refers to a thread of execution, waits for that thread of execution to complete, the time `wait_until` hasbeen reach or the specified duration `rel_time` has elapsed. If `*this` doesn't refer to a thread of execution, returns immediately.]][[Returns:] [`true` if `*this` refers to a thread of execution on entry, and that thread of execution has completed before the calltimes out, `false` otherwise.]][[Postconditions:] [If `*this` refers to a thread of execution on entry, and `timed_join` returns `true`, that thread of executionhas completed, and `*this` no longer refers to any thread of execution. If this call to `timed_join` returns `false`, `*this` isunchanged.]][[Throws:] [__thread_interrupted__ if the current thread of execution is interrupted.]][[Notes:] [`timed_join()` is one of the predefined __interruption_points__.]]][endsect][section:detach Member function `detach()`] void detach();[variablelist[[Effects:] [If `*this` refers to a thread of execution, that thread of execution becomes detached, and no longer has an associated __thread__ object.]][[Postconditions:] [`*this` no longer refers to any thread of execution.]][[Throws:] [Nothing]]][endsect][section:get_id Member function `get_id()`] thread::id get_id() const;[variablelist[[Returns:] [If `*this` refers to a thread of execution, an instance of __thread_id__ that represents that thread. Otherwise returnsa default-constructed __thread_id__.]][[Throws:] [Nothing]]][endsect][section:interrupt Member function `interrupt()`] void interrupt();[variablelist[[Effects:] [If `*this` refers to a thread of execution, request that the thread will be interrupted the next time it enters one ofthe predefined __interruption_points__ with interruption enabled, or if it is currently __blocked__ in a call to one of thepredefined __interruption_points__ with interruption enabled .]][[Throws:] [Nothing]]] [endsect][section:hardware_concurrency Static member function `hardware_concurrency()`] unsigned hardware_concurrency();[variablelist[[Returns:] [The number of hardware threads available on the current system (e.g. number of CPUs or cores or hyperthreading units),or 0 if this information is not available.]][[Throws:] [Nothing]]][endsect][section:nativehandle Member function `native_handle()`] typedef platform-specific-type native_handle_type; native_handle_type native_handle();[variablelist[[Effects:] [Returns an instance of `native_handle_type` that can be used with platform-specific APIs to manipulate the underlyingimplementation. If no such instance exists, `native_handle()` and `native_handle_type` are not present.]][[Throws:] [Nothing.]]][endsect][section:equals `operator==`] bool operator==(const thread& other) const;[variablelist[[Returns:] [`get_id()==other.get_id()`]]][endsect][section:not_equals `operator!=`] bool operator!=(const thread& other) const;[variablelist[[Returns:] [`get_id()!=other.get_id()`]]][endsect][section:sleep Static member function `sleep()`] void sleep(system_time const& abs_time);[variablelist[[Effects:] [Suspends the current thread until the specified time has been reached.]][[Throws:] [__thread_interrupted__ if the current thread of execution is interrupted.]][[Notes:] [`sleep()` is one of the predefined __interruption_points__.]]][endsect][section:yield Static member function `yield()`] void yield();[variablelist[[Effects:] [See [link thread.thread_management.this_thread.yield `boost::this_thread::yield()`].]]][endsect][section:swap Member function `swap()`] void swap(thread& other);[variablelist[[Effects:] [Exchanges the threads of execution associated with `*this` and `other`, so `*this` is associated with the thread ofexecution associated with `other` prior to the call, and vice-versa.]][[Postconditions:] [`this->get_id()` returns the same value as `other.get_id()` prior to the call. `other.get_id()` returns the samevalue as `this->get_id()` prior to the call.]][[Throws:] [Nothing.]]][endsect][section:non_member_swap Non-member function `swap()`] #include <boost/thread/thread.hpp> void swap(thread& lhs,thread& rhs);[variablelist[[Effects:] [[link thread.thread_management.thread.swap `lhs.swap(rhs)`].]]][endsect][section:id Class `boost::thread::id`] #include <boost/thread/thread.hpp> class thread::id { public: id();
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?