您的位置:首页 > 运维架构 > Linux

linux下线程的创建和等待

2011-10-15 12:41 316 查看
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.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 the cpu time");//注意线程退出函数
}

int main()
{
int res;
pthread_t a_thread; //新线程的标识符
void *thread_result;//定义一个线程返回值
res=pthread_create(&a_thread,NULL,thread_function,(void *)message);//创建线程
if(res!=0)//线程创建不成功
{
perror("Thread create error!");
exit(EXIT_FAILURE);
}
printf("waiting for thread to finish...\n");
res=pthread_join(a_thread,&thread_result);//等待新线程结束
if(res!=0)
{
perror("Thread join error!");
exit(EXIT_FAILURE);
}
printf("Thread joined , it returned %s\n",(char *)thread_result);
printf("Message is now %s\n",message);
exit(EXIT_SUCCESS);
}




注意,多线程的编译和普通程序的编译是不一样的,要用这样的命令: 【cc -D_REENTRANT thread.c -g -o thread -lpthread】

大家可以看到,全局变量message经过线程创建函数传递给线程函数后由【hello world】变成了【Bye!】

res=pthread_join(a_thread,&thread_result);//等待新线程结束
等待新线程结束,只有新线程结束后才会向下执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息