#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.o
gcc -o test thread.o -lpthread
thread.o:thread.c
gcc -c thread.c
clean:
rm test *.o