linux下线程的创建和管理

来源:互联网 发布:seo编辑工具 编辑:程序博客网 时间:2024/06/01 20:55
#include<stdio.h>#include<stdlib.h>#include<pthread.h>#include<string.h>char msg[]="Hello";void* thread_function(void*);int main(){    int res=-1;    pthread_t th={0};    printf("the mem is %s\n",msg);    res=pthread_create(&th,NULL,thread_function,(void*)msg);    if(0!=res)    {        printf("sorry the thread create failed\n");        exit(0);    }    //开始合并线程,也即等待线程执行完之后才能继续向下执行,thread_res是pthread_exit中的值    void* thread_res=NULL;    res=pthread_join(th,&thread_res);    if(0!=res)    {        printf("thread_join failed \n");        exit(0);    }    printf("thread exit successfully!the return is :%s\n",(char*)thread_res);    printf("the mem is %s\n",msg);    exit(0);    return 0;}void* thread_function(void* msg){    printf("this is thread output\n");    //休眠3秒    sleep(3);    strcpy((char*)msg,"youto");    pthread_exit("线程执行完毕");}

恩,恩,还有对应的makefile文件如下:

test: thread.ogcc -o test thread.o  -lpthreadthread.o:thread.cgcc -c thread.cclean:rm test *.o


0 0
原创粉丝点击