C/C++教程

c++11 thread(初步)

本文主要是介绍c++11 thread(初步),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

为什么会写这篇博客呢,原因是因为我在学 thrift 的时候 要写多线程,而我都没有学过,所以有了这篇博客。

官方的thread文档

Thread

Class to represent individual threads of execution.

A thread of execution is a sequence of instructions that can be executed concurrently with other such sequences in multithreading environments, while sharing a same address space.

An initialized thread object represents an active thread of execution; Such a thread object is joinable, and has a unique thread id.

A default-constructed (non-initialized) thread object is not joinable, and its thread id is common for all non-joinable threads.

A joinable thread becomes not joinable if moved from, or if either join or detach are called on them.

下面是官方的例子

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread
void foo()
{
  // do stuff...
}
void bar(int x)
{
  // do stuff...
}
int main()
{
  std::thread first (foo);     // spawn new thread that calls foo()
  std::thread second (bar,0);  // spawn new thread that calls bar(0)
  std::cout << "main, foo and bar now execute concurrently...\n";
  // synchronize threads
  first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes
  std::cout << "foo and bar completed.\n";
  return 0;
}

如果直接拿这个例子,去测试的话,会报错的。
我是Linux的基础上编译链接的
image

链接的时候要加 -pthread,不然找不到这个
image
运行后
image

这篇关于c++11 thread(初步)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!