您的位置:首页 > 其它

创建一个线程_续

2013-12-29 20:27 134 查看
/*************************************************************************
> File Name: thread_create.c
> Author: laiyehua
> Mail: ok.4444@qq.com
> Created Time: Sun 29 Dec 2013 11:00:32 AM CST
************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>

/**************************************************************
* 函数功能:显示线程相应函数执行结果
* 参数一:返回结果
* 参数二:执行函数
*************************************************************/
void disp_state_message(int ret, char *msg)
{
/*线程函数基本上返回0表示成功*/
if(ret != 0)
{
printf("%s error\n", msg);
exit(EXIT_FAILURE);
}
}

/****************************************************************
* 函数功能:新创建的线程开始执行的函数
* 参数一:线程创建时,传递过来参数
* 返回:线程退出时,返回的值
***************************************************************/
void *thread_function(void *arg)
{
printf("thread_function runing..............\n");
printf("%s\n", (char *)arg);
pthread_exit("hi!");
}

int main(void)
{
int ret;//返回结果
pthread_t tid;//创建线程ID号
void *result;

ret = pthread_create(&tid, NULL, thread_function, "hello thread_function!");//新创建一个线程,给线程传递参数"hello thread_function!"
disp_state_message(ret, "pthread_create");//显示创建结果

printf("main runing..............\n");

//usleep(1000);//让出本线程,让其它线程有机会执行

ret = pthread_join(tid, &result);//等待线程结果,如果创建的线程不是分离线程,应该使用这个函数回收线程的资源
disp_state_message(ret, "pthread_join");
printf("result:%s\n", (char *)result);

exit(EXIT_SUCCESS);

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