zoukankan      html  css  js  c++  java
  • 线程的创建,pthread_create,pthread_self,pthread_once

    typedef unsigned long int pthread_t;
    //come from /usr/include/bits/pthreadtypes.h

    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);创建新的线程

    pthread_t pthread_self(void);获取本线程的线程ID

    int pthread_equal(pthread_t t1, pthread_t t2);判断两个线程ID是否指向同一线程

    int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));用来保证init_routine线程函数在进程中只执行一次。

    #include <stdio.h>
    #include <pthread.h>
    #include <unistd.h>
    #include <stdlib.h>
    
    
    
    int* thread_func(void* arg)
    {
        pthread_t new_thid;
        new_thid = pthread_self();//打印线程自己的线程ID
        printf("the new thread, ID is %lu
    ", new_thid);
    
        return NULL;
    }
    
    
    int main()
    {
        pthread_t thid;
    
        printf("main thread, ID is %lu
    ", pthread_self());//打印主线程自己的线程ID
    
        if (pthread_create(&thid, NULL, (void*)thread_func, NULL) != 0)
        {
            printf("create thread failed
    ");
            exit(0);
        }
    
        
        sleep(5);
    
        return 0;
    }

    某些情况下,函数执行次数要被限制为1次,这种情况下,要使用pthread_once,代码示例:

    #include <stdio.h>
    #include <pthread.h>
    #include <unistd.h>
    #include <stdlib.h>
    
    
    pthread_once_t once = PTHREAD_ONCE_INIT;
    
    void run(void)
    {
        printf("function run is running in thread:%lu
    ", pthread_self());
    }
    
    
    int* thread1(void* arg)
    {
        pthread_t new_thid;
        new_thid = pthread_self();
        printf("current thread ID is %lu
    ", new_thid);
        pthread_once(&once, run);
        printf("thread1 end
    ");
        return NULL;
    }
    
    int* thread2(void* arg)
    {
        pthread_t new_thid;
        new_thid = pthread_self();
        printf("current thread ID is %lu
    ", new_thid);
        pthread_once(&once, run);
        printf("thread2 end
    ");
        return NULL;
    }
    
    int main()
    {
        pthread_t thid1, thid2;
    
        printf("main thread, ID is %lu
    ", pthread_self());
    
        pthread_create(&thid1, NULL, (void*)thread1, NULL);
        pthread_create(&thid2, NULL, (void*)thread2, NULL);
        
        sleep(5);    
        printf("main thread exit
    ");
    
        return 0;
    }

    运行结果:

    main thread, ID is 3076200128
    current thread ID is 3067804480
    function run is running in thread:3067804480
    thread2 end
    current thread ID is 3076197184
    thread1 end
    main thread exit

    虽然在thread1 跟thread2中都调用了run函数,但是run函数只执行了一次。

  • 相关阅读:
    理解 CSS3中 object-fit
    CSS布局总结(一)
    Webpack 学习记录之概念
    python中深浅拷贝
    Vue中的动画封装
    Vue中的列表过渡
    Vue中多个元素或组件的过渡
    Vue中的Js动画与Velocity.js 的结合
    在Vue中同时使用过渡和动画
    在Vue中使用 animate.css 库
  • 原文地址:https://www.cnblogs.com/zhangxuan/p/6429430.html
Copyright © 2011-2022 走看看