c++11多线程编程(一):创建线程的三种方法

c++11线程库

原始的c++标准仅支持单线程编程,新的c++标准(c++11或c++0x)于2011年发布,引入了新的线程库。


编译器要求
Linux: gcc 4.8.1 (完全并发支持)
Windows: Visual Studio 2012 and MingW


在linux下的编译方法:g++ -std=c++11 sample.cpp -lpthread


在c++11中创建线程
在每个c++应用程序中,都有一个默认的主线程,即main函数,在c++11中,我们可以通过创建std::thread类的对象来创建其他线程,每个std :: thread对象都可以与一个线程相关联。
需包含头文件<thread>


std :: thread对象将执行什么?

我们可以使用std :: thread对象附加一个回调,当这个新线程启动时,它将被执行。 这些回调可以是,
1、函数指针
2、函数对象
3、Lambda函数


线程对象可以这样创建
std::thread thObj(<CALLBACK>)

新线程将在创建新对象后立即开始,并且将与已启动的线程并行执行传递的回调。
此外,任何线程可以通过在该线程的对象上调用join()函数来等待另一个线程退出。


看一个主线程创建单独线程的例子,创建完新的线程后,主线程将打印一些信息并等待新创建的线程退出。

使用函数指针创建线程:

#include <iostream>
#include <thread>

void thread_function() {
  for (int i = 0; i < 100; i++)
    std::cout << "thread function excuting" << std::endl;
}

int main() {
  std::thread threadObj(thread_function);
  for (int i = 0; i < 100; i++)
    std::cout << "Display from MainThread" << std::endl;
  threadObj.join();
  std::cout << "Exit of Main function" << std::endl;
  return 0;
}


使用函数对象创建线程:

#include <iostream>
#include <thread>

class DisplayThread {
 public:
  void operator ()() {
    for (int i = 0; i < 100; i++)
      std::cout << "Display Thread Excecuting" << std::endl;
  }
};

int main() {
  std::thread threadObj((DisplayThread()));
  for (int i = 0; i < 100; i++)
    std::cout << "Display From Main Thread " << std::endl;
  std::cout << "Waiting For Thread to complete" << std::endl;
  threadObj.join();
  std::cout << "Exiting from Main Thread" << std::endl;

  return 0;
}


线程间的区分

每个std::thread对象都有一个相关联的id,可以获取到
std::thread::get_id() :成员函数中给出对应线程对象的id
std::this_thread::get_id() : 给出当前线程的id
如果std::thread对象没有关联的线程,get_id()将返回默认构造的std::thread::id对象:“not any thread”
std::thread::id也可以表示id

示例:

#include <iostream>
#include <thread>

void thread_function() {
  std::cout << "inside thread :: ID = " << std::this_thread::get_id() << std::endl;
}

int main() {
  std::thread threadObj1(thread_function);
  std::thread threadObj2(thread_function);

  if (threadObj1.get_id() != threadObj2.get_id()) {
    std::cout << "Both Threads have different IDs" << std::endl;
  }
  std::cout << "From Main Thread :: ID of Thread 1 = " << threadObj1.get_id() << std::endl;
  std::cout << "From Main Thread :: ID of Thread 2 = " << threadObj2.get_id() << std::endl;

  threadObj1.join();
  threadObj2.join();

  return 0;
}


  • 23
    点赞
  • 98
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值