学习《POSIX多线程程序设计》笔记一

/*
 * lifecycle.c
 *
 * Demonstrate the "life cycle" of a typical thread. A thread is
 * created, and then joined.
 */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
//#include "errors.h"

/*
 * Thread start routine.
 */
void thread_routine (void)
{
    int i =0;
    for(i=0;i<10;i++)
    {
        printf(" i :%d  \n",i);
        sleep(2);
    }
    //退出 //里面可以写退出信息
    pthread_exit("");
}

void thread_routine_one (void)
{
    int i =0;
    for(i=0;i<15;i++)
    {
        printf("ii: %d  \n",i);
        sleep(2);
    }
    pthread_exit("");
}

int main (int argc, char *argv[])
{
    pthread_t thread_id ,thread_id2;
    void *thread_result;
    int status;
    //创建成功返回0 //并开始运行 thread_routine //书中此处错误//等于0 才是创建成功
    //第一个参数为指向线程标识符的指针。
//第二个参数用来设置线程属性。
//第三个参数是线程运行函数的起始地址。
//最后一个参数是运行函数的参数。
    status = pthread_create (&thread_id, NULL, (void *)thread_routine, NULL);
    if (status == 0)
    {
        printf("Create thread %d\n",thread_id);
    }
     status = pthread_create (&thread_id2, NULL, (void *)thread_routine_one, NULL);
    if (status == 0)
    {
        printf("Create thread %d\n",thread_id2);
    }
    //阻塞   如果thread_id 没结束  就会一直阻塞在这里
    status = pthread_join (thread_id2, &thread_result);
    if (status == 0)
    {
       // err_abort (status, "Join thread");
        printf("Join thread %d \n",thread_id2);
    }

    status = pthread_join (thread_id, &thread_result);
    if (status == 0)
    {
        printf("Join thread %d\n",thread_id);
    }
    return 0;
}




//---------- 下面一段代码是独立的,主要测试 pthread_join的第二个参数-------------------------


//pthread_join的第二个参数的解释
//输出线程的退出的消息
#include <stdio.h>
#include <pthread.h>
void thread1(char s[])
{ 
   pthread_exit("hello");  //结束线程,返回一个值。
}
int main(void) 
{
        pthread_t id1;
        void *a1;
        int i,ret1;
        char s1[]="This is first thread!";
        ret1=pthread_create(&id1,NULL,(void *) thread1,s1);
        pthread_join(id1,&a1);
        printf("%s\n",(char*)a1);  //输出hello //是线程的退出信息
        return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值