C++11之thread线程

今天由于项目需求(其实是某门课的一个大作业,不好意思说出口啊。。。),想要使用多线程。相信大家一般用的是linux上的POSIX C或windows上的线程库,然而这些线程库以来于特定系统,并不“标准”。2011年发布的C++11标准中提供了并发执行的相关操作:

C++11 新标准中引入了四个头文件来支持多线程编程,他们分别是<atomic> ,<thread>,<mutex>,<condition_variable>和<future>。

  • <atomic>:该头文主要声明了两个类, std::atomic 和 std::atomic_flag,另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。<thread>:该头文件主要声明了 std::thread 类,另外 std::this_thread 命名空间也在该头文件中。
  • <mutex>:该头文件主要声明了与互斥量(mutex)相关的类,包括 std::mutex 系列类,std::lock_guard, std::unique_lock, 以及其他的类型和函数。
  • <condition_variable>:该头文件主要声明了与条件变量相关的类,包括 std::condition_variable 和 std::condition_variable_any。
  • <future>:该头文件主要声明了 std::promise, std::package_task 两个 Provider 类,以及 std::future 和 std::shared_future 两个 Future 类,另外还有一些与之相关的类型和函数,std::async() 函数就声明在此头文件中。

std::thread 之"Hello world":

#include <iostream> 
#include <thread>   // std::thread

void thread_task() {//同其他线程库一样,返回值类型为void
    std::cout << "hello thread" << std::endl;
}

int main(int argc, char *argv[])
{
    std::thread t(thread_task);
    t.join();//类似java里的start()

    return EXIT_SUCCESS;
}

编译时注意:加上-std=c++0x (新标准) -lpthread 因为GCC默认没有加载 pthread 库,我现在用的GCC4.6,也许以后的版本就不用这么麻烦了。

如果忘加-lpthread会提示:terminate called after throwing an instance of 'std::system_error'
             what(): Operation not permitted
             已放弃 (核心已转储)

可以写个makefile方便编译,一劳永逸:

all:myThread

CC=g++
CPPFLAGS=-Wall -std=c++0x -ggdb
LDFLAGS=-pthread

myThread:myThread.o
    $(CC) $(LDFLAGS) -o $@ $^

myThread.o:myThread.cc
    $(CC) $(CPPFLAGS) -o $@ -c $^


.PHONY:
    clean

clean:
    rm myThread.o myThread
原文地址:https://www.cnblogs.com/makefile/p/3798328.html