1.pthread_create()初体验

来源:互联网 发布:下载火车购票软件 编辑:程序博客网 时间:2024/05/17 02:46

先来看看程序吧

#include <stdio.h>#include <stdlib.h>#include <pthread.h>void *sayhello(void *arg){    printf("hello, world! I'm son\n");}int main(void){    pthread_t son;    pthread_create(&son, NULL, sayhello, NULL);    printf("hello, world! I'm father\n");    return 0;}
关于pthread_create()函数的介绍,此处略过!

关于编译多线程程序

有几点值得注意:

1.头文件必须要引用pthread.h文件,此文件我也不知道在哪里,linux内核源码中是找不到了,或许在编译器中吧;

2.编译时必须要链接pthread库,如:

“gcc -o main main.c -lpthread”

3.线程对应的函数的格式必须是这样:void *xxoo(void *arg)

a.把“void *sayhello(void *arg)”改成“void sayhello(void *arg)”会报错如下:

root@book-desktop:/opt/pc_test/multithreading/1# make

gcc -o main main.c -lpthread

main.c: In function ‘main’:

main.c:14: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type

/usr/include/pthread.h:227: note: expected ‘void * (*)(void *)’ but argument is of type ‘void (*)(void *)’

b.把“void *sayhello(void *arg)”改成“void *sayhello(void)”会报错如下:

root@book-desktop:/opt/pc_test/multithreading/1# make

gcc -o main main.c -lpthread

main.c: In function ‘main’:

main.c:14: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type

/usr/include/pthread.h:227: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(void)’

接着来执行一下程序,结果如下:

root@book-desktop:/opt/pc_test/multithreading/1# ./main 

hello, world! I'm father

纳尼!“hello, world! I'm son”咋个没出现?这是什么原因呢?

有文曰“进程的终止可以通过在主函数main()中直接调用exit、return、或者通过进程中的任何其它线程调用exit来实现。在任何一种情况下,该进程的所有线程都会终止。如果主线程在创建了其它线程之后没有工作可做,或者说主线程有必要等到其他线程都结束才结束的情况下,主线程应该阻塞到所有线程都结束为止。”

soga!这就有得解释了,上述程序中,打印“hello, world! I'm father”是父线程的任务,打印“hello, world! I'm son”是子线程要做的事情,父线程在创建子线程之后,父线程和子线程都有机会被内核调用,可是,也许因为某些原因,父线程先被调用,父线程的内容很少,瞬间就调用完了,此时子线程还没来及被调用,父线程就碰到了“return 0”这条语句,所以整个进程就被终止了。

怎么破?也即让“printf("hello, world! I'm son\n");”和“printf("hello, world! I'm father\n");”都能够执行。至少有如下这么一些方法:

方法1:在“return 0;”之前加上一句“sleep(1);”

方法2:在“父线程”所对应程序中加上一句“pthread_join(son)”

方法3:在“父线程”所对应程序中加上一句“pthread_exit(NULL)”

方法1使得父线程有1秒钟的睡眠时间,此时子线程就有足够的时间和机会被内核调用了;

方法2使得父线程在结束之前得“等到”子线程(thread son)执行完毕;

方法3中pthread_exit()本身的作用“终止调用它的线程,但在此之前,它会等待子线程全部执行完”,所以若把pthread_exit(NULL)放在main函数的return之前,它的效果和“pthread_join(son1, NULL);;pthread_join(son2, NULL);pthread_join(son3, NULL)...”差不多!

更多的此处就不讲了,后面接着说...

原创粉丝点击