linux下 多线程的使用

来源:互联网 发布:c语言打印long 编辑:程序博客网 时间:2024/05/29 18:33
因为最近在看slam的程序,在里面发现了<thread>,所以想了解下多线程,本以为跑通一个demo 很简单的,但是实际的操作还是有点小坑的。最初是希望使用thread,因为网上资料显示它是对pthread做了封装的一个库,对于我仅仅简单的使用下当然是最好了,但是后来搜索了一圈thread的资料好少。只好先上pthread。在QT环境下只需要添加上它的库就好了,LIBS += -lpthread
#include <unistd.h>#include <pthread.h>#include <stdio.h>#define NUM 10int count;void* thread_func(void *arg){    count++;    printf("count %d\n", count);//    return;}int main(){    pthread_t tid[NUM];    int i = 0;    for (i = 0; i < NUM; i++)    {        pthread_create(&tid[i], NULL, thread_func, NULL);    }    sleep(1);    return 0;}

如果希望直接使用gcc编译也可以,但是在终端编译的时候要加上-lpthread.

gcc Test.cpp -o test -lpthread

最后我希望在cmake 中使用它,所以必须在CMakeLists.txt中加入如下的库:

cmake_minimum_required(VERSION 2.8)project(thread_test)add_definitions(-std=c++11)set (CMAKE_CXX_STANDARD 11)add_executable(thread Test.cpp)target_link_libraries(thread pthread)

这样pthread就可以在多个编译器下进行编译了。
但是我看的ORB_SLAM2里面直接引用的就是#include ,很蛋疼,看它的cmakelists.txt也没看出什么问题。只能再查下资料了。