zoukankan      html  css  js  c++  java
  • posix线程库1

    posix线程库重要的程度不言而喻,这些天学习这个,参考 https://www.ibm.com/developerworks/cn/linux/thread/posix_thread1/
     
    首先先看第一个基本的程序

    #include <stdio.h>

    #include <pthread.h>

    #include <stdlib.h>

    #include <unistd.h>

     

    void * thread_function(void * arg)

    {

        int i ;

        for (i=0; i<20; i++) {

            printf("thread says hi! ");

            sleep(1);

        }

        return NULL;

    }

     

    int main(int argc, const char * argv[])

    {

        pthread_t mythread;

        if (pthread_create(&mythread, NULLthread_functionNULL)) {

            printf("error creating thread.");

            abort();

        }

        if (pthread_join(mythread, NULL)) {

            printf("error joining thread");

            abort();

        }

        return 0;

    }

    对于要使用posix线程库要引用头文件<pthread.h>,里面所有的函数都是以pthread_t开头。

    看main函数,定义一个pthread_t保存线程的ID,具体的结构可以进去看看,大概就是一个结构体如下

    struct _opaque_pthread_t { long __sig; struct __darwin_pthread_handler_rec  *__cleanup_stack; char __opaque[__PTHREAD_SIZE__]; };

     
    下面就是创建一个线程pthread_create,看一看其定义

    int       pthread_create(pthread_t * __restrict,

                             const pthread_attr_t * __restrict,

                             void *(*)(void *),

                             void * __restrict);

     
    第一个参数存放线程的ID,
    第二个参数可用来定义线程的某些属性。由于缺省的线程属性是适用的,只需将该参数设为 NULL。
    第三个参数是线程开始执行时调用的函数的名字。函数的格式必须如下:
    void * f(void * arg)
    对于上述程序中函数名为thread_function。当thread_function()返回时,线程将终止。返回的void指针将被pthread_join函数当成退出状态来处理。
    第四个参数是传递函数f的参数。
    对于pthread_create创建成功返回0,不成功返回一个非零的错误码,因此上面放在if上面判断。
     
    好,当pthread_create创建成功之后,程序有了两个线程,主程序同样是一个线程,主程序仍然执行,另外一个线程执行完成之后,先停止后与另外的线程合并。
     
    下面执行pthread_join,pthread_create是将一个线程分成两个线程,pthread_join是将两个线程合并成一个线程。这个函数将调用这个函数的线程等待指定的线程运行完成再继续执行。

    int       pthread_join(pthread_t , void **)

    第一个参数为要等待的线程Id

    第二个参数给指向返回值的指针提供一个位置,如果为NULL,则我们就不用关心其返回值是啥了

    pthread_join就是等待另外的线程执行完成,进行线程合并。这个是有必要的,要注意对线程合理的释放,不然最后可能会导致创建失败。

  • 相关阅读:
    SUSE10 SP2/SP3 无规律死机故障解决
    随机铃声
    linux添加开机启动项
    SUSE Linux ShutdownManager issue
    linux添加开机启动项
    两个正在运行的activity之间的通信
    android 获取屏幕大小
    Linux开机启动过程分析
    grid的宽度设为100%问题
    动态处理editGridPanel
  • 原文地址:https://www.cnblogs.com/fengbing/p/3305634.html
Copyright © 2011-2022 走看看