c++ multithread and lock--part 2

本文将对<thread>库进行详细的介绍

class std::thread

std::thread是c++11开始提供的标准线程库,std::thread实质上是对POSIX线程进行了封装,在不同平台上对用户是透明的。thread类主要提供了以下几个方法:

#include <iostream>
#include <thread>
#define TEST(X)        \
  void test##X() {   \
  }
TEST(1)
TEST(2)
int main() {
   std::thread t1(test1);
   std::thread t2(test2);
   std::cout << " the id of t1 = " << t1.get_id() << std::endl;
   std::cout << " the id of t2 = " << t2.get_id() << std::endl;
   std::cout << " ------------------AFTER SWAP---------------" << std::endl;
   t1.swap(t2);
   std::cout << " the id of t1 = " << t1.get_id() << std::endl;
   std::cout << " the id of t2 = " << t2.get_id() << std::endl;

   return 0;
}

运行结果:

 the id of t1 = 0x70000efc3000
 the id of t2 = 0x70000f046000
 ------------------AFTER SWAP---------------
 the id of t1 = 0x70000f046000
 the id of t2 = 0x70000efc3000
  • joinable(),用于判断线程对象是否是可join的,方法的返回值是bool类型的。当一个线程处于运行状态那么它是可join的,一个线程在以下三种情况下是不可join的:
    (1)由默认构造函数构造
    (2)通过移动构造
    (3)已经调用了join()或detach()方法
    使用代码如下:
#include <iostream>
#include <thread>

#define TEST(X)        \
   void test##X() {   \
   }

TEST(2)
TEST(3)
TEST(4)

class thread_wrap : public std::thread {
public:
    thread_wrap(std::function<void()> callback) : std::thread(callback){
    }
    thread_wrap() : std::thread(){
    }
    std::string joinable_wrap() {
        std::string result;
        if(joinable()) {
            return "true";
        }
        return "false";
    }
};

int main() {
    // thread_wrap t1();
    thread_wrap t2(test2);
    t2.join();
    thread_wrap t3(test3);
    t3.detach();
    thread_wrap t4(test4);

    // std::cout << " the joinable of t1 = " << t1.joinable_wrap() << std::endl;
    std::cout << " the joinable of t2 = " << t2.joinable_wrap() << std::endl;
    std::cout << " the joinable of t3 = " << t3.joinable_wrap() << std::endl;
    std::cout << " the joinable of t4 = " << t4.joinable_wrap() << std::endl;

    return 0;
}

运行结果:

 the joinable of t2 = false
 the joinable of t3 = false
 the joinable of t4 = true
  • native_handle(),持有的pthread对象。
  • hardware_concurrency(),用于查询机器上有多少个CPU,返回值是unsigned类型。

namespace std::this_thread

类std::thread的所有辅助函数均位于this_thread的命名空间中,如:

namespace this_thread{
  thread::id get_id() _NOEXCEPT;
  inline void yield()  _NOEXCEPT;
  template<class _Rep, class _Period> inline 
  void sleep_for(const chrono::duration<_Rep, _Period>& __d);
  template<class _Clock, class _Duration> inline
  void sleep_until(const chrono::time_point<_Clock, _Duration>& __t);
}

yield(),当前线程让出cpu资源,提供提示给实现,以重新调度线程的执行,允许其他线程运行。在当前线程执行过程中某一必须条件暂时还不满足时,使用 std::this_thread::yield() , 将其未使用完的CPU资源让出给其他线程使用, 等到其他线程用完后, 再和其他线程一起竞争使用,这样可以避免cpu资源的无效占用而影响程序运行性能。

#include <iostream>
#include <chrono>
#include <thread>
 
void test_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();
 
    test_sleep(std::chrono::microseconds(100));
 
    auto elapsed = std::chrono::high_resolution_clock::now() - start;
    std::cout << "waited for "
              << std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count()
              << " microseconds\n";
}

sleep_for(), 将当前线程休眠一段时间,不再与其他线程争抢cpu资源,但是并不让出当前占用的cpu资源。

#include <iostream>       // std::cout, std::endl
#include <thread>         // std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds
 
int main() 
{
  std::cout << "countdown:\n";
  for (int i=10; i>0; --i) {
    std::cout << i << std::endl;
    std::this_thread::sleep_for (std::chrono::seconds(1));
  }
  std::cout << "Lift off!\n";

  return 0;
}

sleep_until(),将当前线程阻塞至某一时间点之后。在这一过程中不再与其他线程争抢cpu资源,但是并不让出当前占用的cpu资源。

 #include <iostream>       // std::cout
#include <iomanip>        // std::put_time
#include <thread>         // std::this_thread::sleep_until
#include <chrono>         // std::chrono::system_clock
#include <ctime>          // std::time_t, std::tm, std::localtime, std::mktime

int main() 
{
  using std::chrono::system_clock;
  std::time_t tt = system_clock::to_time_t (system_clock::now());
  struct std::tm * ptm = std::localtime(&tt);
  std::cout << "Current time: " << std::put_time(ptm,"%X") << '\n';

  std::cout << "Waiting for the next minute to begin...\n";
  ++ptm->tm_min; ptm->tm_sec=0;
  std::this_thread::sleep_until (system_clock::from_time_t (mktime(ptm)));

  std::cout << std::put_time(ptm,"%X") << " reached!\n";
  return 0;
}

参考链接:
http://www.cplusplus.com/reference/multithreading/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容