[关闭]
@zhengyuhong 2015-06-08T02:00:02.000000Z 字数 6063 阅读 1160

thread

C++11 Boost STL


thread

thread::thread

  1. #include <thread>
  2. using std::thread;
  1. thread() noexcept;
  1. template <class Fn, class... Args>
  2. explicit thread (Fn&& fn, Args&&... args);
  3. //fn可以是一个函数指针、function实例、重载了operator()的functor、lambda函数,后面的变长参数args是fn的参数
  1. thread (const thread&) = delete; //copy [deleted] 禁止拷贝构造函数的生成,另一种禁止产生技术是拷贝构造函数私有化
  1. thread (thread&& x) noexcept; //move (4)

example.cpp

  1. // constructing threads
  2. #include <iostream> // std::cout
  3. #include <chrono> // std::chrono::seconds
  4. #include <thread> // std::thread
  5. #include <vector> // std::vector
  6. #include <functional> //std::function
  7. int f(int n) {
  8. auto thread_id = std::this_thread::get_id();
  9. //获取当前线程空间的线程id,类型是std::thread::id,简单使用auto类型推导
  10. for(int i=0; i < n; ++i) {
  11. std::cout<<"thread_id "<<thread_id<<" "<<i<<std::endl;
  12. std::this_thread::sleep_for(std::chrono::seconds(1));
  13. //this_thread::sleep_for 当前线程空间下执行sleep_for
  14. }
  15. return 0;
  16. }
  17. g = [](int n) {
  18. auto thread_id = std::this_thread::get_id();
  19. for(int i=0; i < n; ++i) {
  20. std::cout<<"thread_id "<<thread_id<<" "<<i<<std::endl;
  21. std::this_thread::sleep_for(std::chrono::seconds(1));//sleep 1 second
  22. }
  23. return 0;
  24. }
  25. class H {
  26. public:
  27. int operator()(int n) {
  28. auto thread_id = std::this_thread::get_id();
  29. for(int i=0; i < n; ++i) {
  30. std::cout<<"thread_id "<<thread_id<<" "<<i<<std::endl;
  31. std::this_thread::sleep_for(std::chrono::seconds(1));//sleep 1 second
  32. }
  33. return 0;
  34. }
  35. };
  36. int main ()
  37. {
  38. H h;
  39. std::function<int(int)> j(f);
  40. std::thread thread_f(f,10);
  41. std::thread thread_g(g,11);
  42. std::thread thread_h(h,12);
  43. std::thread thread_j(j,13);
  44. return 0;
  45. }

thread::get_id

  1. id get_id() const noexcept;

Get thread id
Returns the thread id.

If the thread object is joinable, the function returns a value that uniquely identifies the thread.

If the thread object is not joinable, the function returns a default-constructed object of member type thread::id, which is empty_id = std::thread()

  1. std::thread::id empty_id1;
  2. std::thread::id empty_id2;
  3. empty_id1 == empty2; // true

提供外部线程获取此线程的thread id,std::this_thread::get_id是获取此线程的thread_id,前者是想知道别的线程的thread_id,后者是想知道自己的threa_id,

thread::operator=

  1. thread& operator= (thread&& rhs) noexcept;
  2. thread& operator= (const thread&) = delete; //也可私有化禁止

Move-assign thread
If the object is currently not joinable, it acquires the thread of execution represented by rhs (if any).

If it is joinable, terminate() is called.

After the call, rhs no longer represents any thread of execution (as if default-constructed).

thread objects cannot be copied (2).

  1. std::thread t;
  2. t = std::thread(f,5);
  3. t.join();
  4. t = std::thread(f,10);

thread::join

  1. void join();

The function returns when the thread execution has completed.
This synchronizes the moment this function returns with the completion of all the operations in the thread: This blocks the execution of the thread that calls this function until the function called on construction returns (if it hasn't yet).
After a call to this function, the thread object becomes non-joinable and can be destroyed safely.
调用方主线程调用线程t的join方法,导致主线程阻塞,直到t线程执行完毕,才返回到主线程中。t.join()结束后,t变成non-joinale,且可以正常销毁了。

thread::joinable

  1. bool joinable() const noexcept;

Check if joinable
Returns whether the thread object is joinable.

A thread object is joinable if it represents a thread of execution.(执行完毕)

A thread object is not joinable in any of these cases:
if it was default-constructed.(std::thread t;)
if it has been moved from (either constructing another thread object, or assigning to it).
if either of its members join or detach has been called.(正在执行,就绪、休眠、阻塞)

thread::detach

  1. void detach();

Detaches the thread represented by the object from the calling thread, allowing them to execute independently from each other.

Both threads continue without blocking nor synchronizing in any way. Note that when either one ends execution, its resources are released.

After a call to this function, the thread object becomes non-joinable and can be destroyed safely.
使线程变成独立线性,不再是守护线程,即使是主线程结束退出,独立线程依然可以继续运行直至结束退出。

thread::swap

  1. void swap (thread& x) noexcept;

  线程虽然不能拷贝,但是可以交换,总之最多只有一个实例指向一个线程即可。
  也可以实现std::swap中的直接交换,因为std::swap的已经对thread进行特丽花。

  1. void swap (thread& x, thread& y) noexcept;
  2. std::thread t1;
  3. std::thread t2;
  4. t1.swap(t2) 等价于 swap(t1,t2);个人更加倾向于第二个

  至此C++11的thread的API已经介绍完毕,剩下的那两个实在不知道什么时候会用上,再参考官方文档吧。

this_thread

this_thread::get_id()

  1. thread::id get_id() noexcept;

Get thread id 获取当前线程空间的线程id
Returns the thread id of the calling thread.
This value uniquely identifies the thread.

this_thread::sleep_for

  1. template <class Rep, class Period>
  2. void sleep_for (const chrono::duration<Rep,Period>& rel_time);

Sleep for time span
Blocks execution of the calling thread during the span of time specified by rel_time.
The execution of the current thread is stopped until at least rel_time has passed from now. Other threads continue their execution.
当前线程休眠一段时间间隔rel_time

  1. std::chrono::duration<Rep,Period>常用的具体类型的实例可做rel_time参数
  2. std::chrono::hours h(1) ; 1 小时;
  3. std::chrono::minutes m(1) ;1 分钟;
  4. std::chrono::seconds s(1) ; 1 秒;
  5. std::chrono::milliseconds mls(1); 1毫秒;
  6. std::chrono::microseconds mcs(1); 微秒;
  7. std::chrono::nanoseconds ns(1); 纳秒;

this_thread::sleep_util

  1. template <class Clock, class Duration>
  2. void sleep_until (const chrono::time_point<Clock,Duration>& abs_time);

Sleep until time point
Blocks the calling thread until abs_time.

The execution of the current thread is stopped until at least abs_time, while other threads may continue to advance.
当前线程休眠到abs_time时间点才唤醒。abs_time是一个时间点,而sleep_for是一个时间间隔
使用time_point需要借助ctime

  1. std::chrono::time_point<Clock,Duration>常用的具体类型:
  2. std::chrono::time_point<std::chrono::system_clock,dtn>
  3. 其中 dtn可取上述的
  4. std::chrono::hours
  5. std::chrono::minutes
  6. std::chrono::seconds
  7. std::chrono::milliseconds
  8. std::chrono::microseconds
  9. std::chrono::nanoseconds
  10. 最常用的的就是
  11. dtn = std::chrono::seconds;
  12. std::chrono::time_point<std::chrono::system_clock,std::chrono::seconds>

example例子

  1. // this_thread::sleep_for example
  2. #include <iostream> // std::cout
  3. #include <iomanip> // std::put_time
  4. #include <thread> // std::this_thread::sleep_until
  5. #include <chrono> // std::chrono::system_clock
  6. #include <ctime> // std::time_t, std::tm, std::localtime,
  7. using std::chrono::time_point;
  8. using std::chrono::system_clock;
  9. using std::system_clock::from_time_t;
  10. using std::tm;
  11. using std::time_t;
  12. using std::mktime;
  13. int main()
  14. {
  15. std::tm tm_tp;
  16. tm_tp.tm_year = 2015 - 1900;
  17. tm_tp.tm_mon = 7; //0是一月,1是二月,···,7是8月
  18. tm_tp.tm_mday = 15;
  19. tm_tp.tm_hour = 19;
  20. tm_tp.tm_min = 19;
  21. tm_tp.tm_sec = 19;
  22. time_t t_tp = mktime(&tm_tp); //得到时间的整数值
  23. time_point<system_clock> chrono_tp = from_time_t(t_tp);
  24. }

std::tm结构 参考struct tm

this_thread::yield

  1. void yield() noexcept;

Yield to other threads
The calling thread yields, offering the implementation the opportunity to reschedule.
This function shall be called when a thread waits for other threads to advance without blocking.
放弃资源,重新加入调度表,可能下一次调度到的线程还是该线程,也可能是其他线程。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注