美文网首页
Linux线程创建

Linux线程创建

作者: sf705 | 来源:发表于2017-11-25 21:19 被阅读161次

    以前都是Windows编程,一直说看看Linux下的线程编程,有空了,回顾一下吧。

    头文件

    Linux下线程相关函数都在头文件 <pthread.h> 中,该头文件中的相关函数在专门的线程库libpthread中,编译的时候需要加上 -lpthread 选项

    一些函数

    pthread_self获取当前线程

    pthread_self(void)  //返回类型为: pthread_t
    

    pthread_equal判断线程是否相同相等

    pthread_equal(pthread_t , pthread_t) // 返回int,非0则相等
    

    pthread_create创建线程

    int pthread_create(pthread_t* pthread, const pthread_attr_t*, void* (*start_routine )(void*), void* arg ) 
    

    成功返回0,错误号表示失败

    • pthread_t 类型变量的thread,线程的标识
    • pthread_attr 线程属性设置,控制线程与程序其他部分交互方式,常设为NULL,默认线程属性
    • start_routine 线程函数指针,是线程要执行的代码,参数为void(*)
    • arg 传递给start_routine的参数(如果需要传递多个参数,常设为一个结构体,将结构体指针传递给线程)

    pthread_cancle线程终止

    int pthread_cancle(pthread_t thread) 
    成功返回0
    

    pthread_join 等待线程终止

    int pthread_join(pthread_t thread, void **ptr) 
    成功返回0,否则失败
    ptr 为返回码,常设为 NULL
    

    代码

    用gcc编译的话,得加上 -lpthread -lstdc++

    #include <iostream>
    #include <unistd.h>
    #include <sys/types.h>
    #include <stdlib.h>
    #include <string.h> //strerror
    #include <pthread.h>
    using namespace std;
    
    static int number = 0;
    
    void printids(const char * s)
    {
        pid_t pid;
        pthread_t tid;  
        pid = getpid(); //获取进程id
        tid = pthread_self(); //获取线程id
        cout << s << " pid " << (unsigned long)pid << " tid " << (unsigned long)tid << endl;
    }
    
    void *run(void* nu) //线程函数,参数得为void*
    {
        int num = *((int*)nu);  
        printids("run1 thread:");
        cout << "get num from param in run1 " << num << endl;
        return ((void *)0); //void* 类型的空指针
    }
    
    void *run2(void*)
    {
        for(int i = 0; i < 3; ++i)
        {
            cout << "run2 thread number : " << ++number << endl;
            sleep(1);
        }
        return NULL;
    }
    
    int main(int argc, char* argv[])
    {
        //pthread_t pthread_self();
        /*pthread_t t1;
        cout << pthread_self() << endl;
        cout << (pthread_t)t1 << endl;*/
    
        pthread_t ntid, tid2; //线程标识
        int num=5;
        int err;
    
        //创建第一个线程,线程函数run,线程函数的参数为num.
        err = pthread_create(&ntid, NULL, run,(void*)(&num));
        sleep(1);
        if(0 != err)
        {
            cout << "cannot create thread: " << strerror(err) << endl;
            exit(1);
        }
    
        //创建第二个线程,线程函数为run2, 函数没有参数
        pthread_create(&tid2, NULL, run2, NULL);
        //加上join,主线程main 会让线程2,也就是run2函数执行完毕后,才会输出最后一句
        pthread_join(tid2, NULL); //如果不加上pthread_join,可能会看不到run2函数执行,main线程先执行完毕
        cout << "main thread number : " << number << endl;
    
        return 0;
    }
    
    

    相关文章

      网友评论

          本文标题:Linux线程创建

          本文链接:https://www.haomeiwen.com/subject/mlfjvxtx.html