linux c++编译

https://blog.csdn.net/qq_20240999/article/details/60870736

 

C++11 自2011年发布以来已经快6年了,之前一直没怎么关注,虽然书上经常看,直到最近几个月才看了一些 C++11 的新特性,今后几篇博客我都会写一些关于 C++11 的特性,算是记录一下自己学到的东西吧,和大家共勉。
相信 Linux 程序员都用过 -pthread, 但有了 C++11 的 std::thread 以后,你可以在语言层面编写多线程程序了,直接的好处就是多线程程序的可移植性得到了很大的提高,所以作为一名 C++ 程序员,熟悉 C++11 的多线程编程方式还是很有益处的。

与 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() 函数就声明在此头文件中。

一个多线程的”hello thread”例子

#include <stdio.h>
#include <stdlib.h>
#include <iostream> // std::cout
#include <thread>   // std::thread
void thread_task() 
{
    std::cout << "hello thread" << std::endl;
}
int main(int argc, const char *argv[])
{
    std::thread t(thread_task);
    t.join();
    return EXIT_SUCCESS;
} 

用shell编译时要加上-pthread参数,否则会报错,例如上面的代码如果没有加-pthread参数:

/tmp/cca41V1k.o: In function `std::thread::thread<void (&)()>(void (&)())':
c.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEEEOT_DpOT0_]+0x21): undefined reference to `pthread_create'
collect2:error: ld returned 1 exit status

 

all:Thread
CC=g++
CPPFLAGS=-Wall -std=c++11 -ggdb
LDFLAGS=-pthread
Thread:Thread.o
    $(CC) $(LDFLAGS) -o $@ $^
Thread.o:Thread.cc
    $(CC) $(CPPFLAGS) -o $@ -c $^
.PHONY:
    clean
clean:
    rm Thread.o Thread
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值