• boost库:多线程


    1.线程管理

    最重要的一个类是boost::thread,是在boost/thread.hpp里定义的,用来创建一个新线程。

    #include <boost/thread.hpp>
    #include <iostream>
    
    void wait(int seconds) {
      boost::this_thread::sleep(boost::posix_time::seconds(seconds));
    }
    
    void thread() {
      for (int i = 0; i < 5; ++i) {
        wait(1);
        std::cout << i << std::endl;
      }
    }
    
    int main() {
      boost::thread t(thread);
      t.join();
      return 0;
    }

    上述执行函数的名称被传递到boost::thread的构造函数,一旦变量t被创建,该thread()函数在其所在线程中被立即执行。join()方法是一个阻塞调用:可以暂停当前线程,直到调用join()的线程结束与你想那个。这会使得main()函数一直会等待到thread()运行结束。

    一个特定的线程可以通过thread变量访问,通过这个变量等待着它的使用join()方法终止,但即使该变量被析构,该线程也将继续运行。

    #include <boost/thread.hpp>
    #include <iostream>
    
    void wait(int seconds) {
      boost::this_thread::sleep(boost::posix_time::seconds(seconds));
    }
    
    void thread() {
      try {
        for (int i = 0; i < 5; ++i) {
          wait(1);
          std::cout << i << std::endl;
        }
      } catch (boost::thread_interrupted&) {
       }
    }
    
    int main() {
      boost::thread t(thread);
      wait(3);
      t.interrupt();
      t.join();
      return 0;
    }

    在一个线程对象上调用interrupt()会中断相应的线程。中断意味着一个类型为boost::thread_interrupted的异常,会在这个线程中抛出,只有在线程达到中断点时才会发生。如果给定的线程不包含任何中断点,简单调用interrupt()就不会起作用。每当一个线程中断点,它就会检查interrupt()是否被调用过。只有被调用过了,boost::thread_interrupted异常才会相应的抛出。sleep()函数为一个程序中断点。

    2. 同步

  • 相关阅读:
    How to Build Office Developer Tools Projects with TFS Team Build 2012
    查看hyper-v主机mac地址
    “Stamping” PDF Files Downloaded from SharePoint 2010
    PostgreSQL体系基本概念
    PostgreSQL 安装
    HDFS+MapReduce+Hive+HBase十分钟快速入门
    光照计算公式
    游戏中的碰撞
    数组
    扑克牌概率
  • 原文地址:https://www.cnblogs.com/sssblog/p/10310937.html
Copyright © 2020-2023  润新知