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!\n");

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

 

转载于:https://www.cnblogs.com/fengbing/p/3305634.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值