linux c/c++多线程程序的编写
第一次尝试编写linux下多线程程序,也是颇废一番周折。深知初学者对能快速的成功运行一段程序的渴望,所以本文专门用了“linux c/c++多线程程序的编写“这个醒目的标题,方便大家能即使从搜索引擎搜到本文,从而提升大家的信心。
首先先让代码进行起来再说为什么,见了效果再回过来头来看原因似乎会容易明白和理解一些。
测试代码如下:
#include[stdio.h] #include[unistd.h] #include[stdlib.h] #include[pthread.h] #include[string.h] void *thread_function(void* arg); char message[] = "Hello world!"; int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_create(&a_thread, NULL, thread_function, (void*)message); if (0 != res) { perror("Thread creation faied"); exit(EXIT_FAILURE); } printf("Waiting for thread to finish...\n"); res = pthread_join(a_thread, &thread_result); if (0 != res) { perror("Thread join failed"); exit(EXIT_FAILURE); } printf("Thread joined, it returned %s\n", (char*)thread_result); printf("Message is now %s\n",message); exit(EXIT_FAILURE); } void *thread_function(void* arg) { printf("thread_function is running. argument was %s\n",(char*)arg); sleep(3); strcpy(message,"bye!"); pthread_exit("Thank you for the cpu time"); }
请将包含头文件的[替换成< ,]替换成>,代码高亮插件会认为尖括号是html标签,所以这里用中括号暂时替代。
编译:
hqlong@ubuntu:~/code/c$ gcc test.c -o test -lpthread
运行
hqlong@ubuntu:~/code/c$ ./test
结果
thread_function is running. argument was Hello world! Waiting for thread to finish... Thread joined, it returned Thank you for the cpu time Message is now bye!
创建进程主要是通过pthread_create()这个函数来创建,函数的定义如下:
int pthread_create ( pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void), void *restrict arg );
返回值:若是成功建立线程返回0,否则返回错误的编号
形式参数:
pthread_t *restrict tidp 要创建的线程的线程id指针
const pthread_attr_t *restrict attr 创建线程时的线程属性
void* (start_rtn)(void) 返回值是void类型的指针函数
vodi *restrict arg start_rtn的行参
注意上面还用到了pthread_join()这个函数,那么这个函数有什么用呢?接下来还是先看看它的原形定义:
int pthread_join ( pthread_t thread, void **value_ptr );
各参数说明如下:
thread 等待退出线程的线程号
value_ptr 退出线程的返回值。
该函数的作用使得当前进程挂起,等待另一个进程返回才继续执行。也就是说当程序运行到这个地方时,程序会先停止,然后等线程id为thread的这个线程返回,然后程序才会断续执行。
在上面的例子中,如果把
res = pthread_join(a_thread, &thread_result); if (0 != res) { perror("Thread join failed"); exit(EXIT_FAILURE); } printf("Thread joined, it returned %s\n", (char*)thread_result);
注释掉,那么主程序根据不会等待线程返回,就退出,当然主进行退出了,他所创建的子进程也就会跟着退出,所以在上面的例子中,程序还在睡眠时,就被主进程强行退出了。
在上面例子进对源码进行编译时,加了-lpthread,如果不加-lprhead,会出现如下编译错误。
tmp/ccnPVTWo.o: In function `main': mthread.c:(.text+0x30): undefined reference to `pthread_create' mthread.c:(.text+0x6f): undefined reference to `pthread_join' collect2: ld returned 1 exit status
thread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a。
更多细节请参考:
http://hi.baidu.com/wenlongren/blog/item/4615450f498006eaaa645759.html
http://hi.baidu.com/wenlongren/blog/item/998f04dd7e866de877c6383e.html
http://blog.sina.com.cn/s/blog_5dcf190f0100dbcm.html
http://hi.baidu.com/beisika/blog/item/8ced51cea7ac9c3eb600c8ea.html
机器人 2009-06-08 18:00 于 北京 阴
机器人 2009-06-09 10:48 于 北京 晴 更新
Hey, nice post, very well written. You should post more about this.