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);//等待新线程结束等待新线程结束,只有新线程结束后才会向下执行。
相关文章推荐
- Linux 线程(创建/等待/终止)
- Linux-线程(一)创建 终止 等待线程
- Linux下多线程编程__线程的创建pthread_create与退出pthread_exit,等待当前线程退出pthread_join,获取线程ID pthread_self
- Linux 在线程中创建线程,在线程中等待线程
- Linux 线程(创建/等待/终止)
- 【Linux】线程(概念、特点、线程控制代码--创建/等待/终止、分离与结合属性)
- Linux下线程的创建与等待
- Linux 线程(创建/等待/终止)
- Linux之线程的创建、等待、终止及分离
- 嵌入式Linux应用程序开发——多线程1(线程的创建和等待)
- [置顶] 【Linux】线程总结:初识、创建、等待、终止、分离
- Linux创建线程
- Linux线程创建以及回调函数的使用
- 使用 线程池,控制线程 , 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待:
- 线程的创建、等待与终止
- Linux 下使用POSIX中为线程创建和同步定义的API时遇到的问题
- linux创建线程时,需注意线程内存回收问题!
- linux下通过模板在创建线程时, 在回调函数中调用不同的类方法
- linux基础编程:多线程基础总结:线程创建 终止 线程同步/互斥量/条件变量/信号灯
- Linux进程线程初探(进程的创建)