创建一个线程_续

/*************************************************************************
	> 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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值