C++11之thread线程

时间:2014-06-28 14:43:56   收藏:0   阅读:233

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

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

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

 

 

C++11之thread线程,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!