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

来源:互联网 发布:战舰世界风神数据 编辑:程序博客网 时间:2024/06/11 02:14
/* * 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;}
0 0