Linux下线程的创建和等待
Linux下线程的创建和等待
- #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");//www.bkjia.com注意线程退出函数
- }
- 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);//等待新线程结束
评论暂时关闭