您的位置:首页 > 其它

线程创建、线程等待、线程终止

2016-12-02 21:16 218 查看
#include <stdio.h>  

#include <pthread.h>  

#include <sys/types.h>  

#include <stdlib.h>  

#include <string.h>  

  

char message[]="hello world!";  

void * thread_function(void *arg)  

{  

    printf("thread function is running, argument is %s\n",(char *)arg);  

    sleep(3);  

    strcpy(message,"bye");  

    pthread_exit("thank you for your CPU time!");  

}  

  

int main()  

{  

    pthread_t a_thread;  

    void * thread_result;  

    int ret;  

      

    ret = pthread_create(&a_thread,NULL,(void *)thread_function,(void *)message);  

  

    if(ret != 0)  

    {  

        perror("create thread error");  

        exit(0);  

    }  

  

    printf("waiting for thread to finish...\n");  

  

    ret = pthread_join(a_thread,&thread_result);  

    if(ret != 0)  

    {  

        perror("thread join error");  

        exit(0);  

    }  

      

    printf("thread joined,it returned %s\n",(char*)thread_result);  

    printf("message is now %s\n",message);  

  

    return 0;  

}  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: