linux中多线程编程的简单示例

来源:互联网 发布:费玉清 爱情买卖知乎 编辑:程序博客网 时间:2024/04/20 11:20

Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux 下pthread的实现是通过系统调用clone()来实现的。clone()是 Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看有关文档说明。下面我们展示一个最简单的 多线程程序 pthread_create.c。


一个重要的线程创建函数原型:
#include <pthread.h>
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类型的指针函数
                void *restrict arg   start_rtn的行参
                
例程1:                               
    功能:创建一个简单的线程
    程序名称:pthread_create.c   

代码如下:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3.   
  4. void *mythread1(void)  
  5. {  
  6.     int i;  
  7.     for(i = 0; i < 10; i++)  
  8.     {  
  9.         printf("This is the 1st pthread,created by xiaoqiang!\n");  
  10.         sleep(1);  
  11.     }  
  12. }  
  13.   
  14. void *mythread2(void)  
  15. {  
  16.     int i;  
  17.     for(i = 0; i < 10; i++)  
  18.     {  
  19.         printf("This is the 2st pthread,created by xiaoqiang!\n");  
  20.         sleep(1);  
  21.     }  
  22. }  
  23.   
  24. int main(int argc, const char *argv[])  
  25. {  
  26.     int i = 0;  
  27.     int ret = 0;  
  28.     pthread_t id1,id2;  
  29.   
  30.     ret = pthread_create(&id1, NULL, (void *)mythread1,NULL);  
  31.     if(ret)  
  32.     {  
  33.         printf("Create pthread error!\n");  
  34.         return 1;  
  35.     }  
  36.   
  37.     ret = pthread_create(&id2, NULL, (void *)mythread2,NULL);  
  38.     if(ret)  
  39.     {  
  40.         printf("Create pthread error!\n");  
  41.         return 1;  
  42.     }  
  43.       
  44.     pthread_join(id1,NULL);  
  45.     pthread_join(id2,NULL);  
  46.   
  47.     return 0;  
  48. }  

执行结果如下:

[cpp] view plain copy
  1. fs@ubuntu:~/qiang/thread$ vi thread1.c  
  2. fs@ubuntu:~/qiang/thread$ gcc -o thread1 thread1.c -lpthread  
  3. fs@ubuntu:~/qiang/thread$ ./thread1  
  4. This is the 2st pthread,created by xiaoqiang!  
  5. This is the 1st pthread,created by xiaoqiang!  
  6. This is the 2st pthread,created by xiaoqiang!  
  7. This is the 1st pthread,created by xiaoqiang!  
  8. This is the 2st pthread,created by xiaoqiang!  
  9. This is the 1st pthread,created by xiaoqiang!  
  10. This is the 2st pthread,created by xiaoqiang!  
  11. This is the 1st pthread,created by xiaoqiang!  
  12. This is the 2st pthread,created by xiaoqiang!  
  13. This is the 1st pthread,created by xiaoqiang!  
  14. This is the 2st pthread,created by xiaoqiang!  
  15. This is the 1st pthread,created by xiaoqiang!  
  16. This is the 1st pthread,created by xiaoqiang!  
  17. This is the 2st pthread,created by xiaoqiang!  
  18. This is the 2st pthread,created by xiaoqiang!  
  19. This is the 1st pthread,created by xiaoqiang!  
  20. This is the 1st pthread,created by xiaoqiang!  
  21. This is the 2st pthread,created by xiaoqiang!  
  22. This is the 2st pthread,created by xiaoqiang!  
  23. This is the 1st pthread,created by xiaoqiang!  
  24. fs@ubuntu:~/qiang/thread$   

两个线程交替执行。
另外,因为pthread的库不是linux系统的库,所以在进行编译的时候要加上-lpthread,否则编译不过,会出现下面错误
thread_test.c: 在函数 ‘create’ 中:
thread_test.c:7: 警告: 在有返回值的函数中,程序流程到达函数尾
/tmp/ccOBJmuD.o: In function `main':thread_test.c:(.text+0x4f):对‘pthread_create’未定义的引用
collect2: ld 返回 1
此例子介绍了创建线程的方法

 

下面例子介绍向线程传递参数。
例程2:
功能:向新的线程传递整形值
程序名称:pthread_int.c

代码如下:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3.   
  4. void *create(void *arg)  
  5. {  
  6.     int *num;  
  7.     num = (int *)arg;  
  8.     printf("Create parameter is %d\n",*num);  
  9.     return (void *)0;  
  10. }  
  11.   
  12. int main(int argc, const char *argv[])  
  13. {  
  14.     pthread_t id1;  
  15.     int error;  
  16.   
  17.     int test = 4;  
  18.     int *attr = &test;  
  19.   
  20.     error = pthread_create(&id1,NULL,create,(void *)attr);  
  21.   
  22.     if(error)  
  23.     {  
  24.         printf("Pthread_create is not created!\n");  
  25.         return -1;  
  26.     }  
  27.     sleep(1);  
  28.   
  29.     printf("Pthread_create is created..\n");  
  30.     return 0;  
  31. }  

执行结果如下:

[cpp] view plain copy
  1. fs@ubuntu:~/qiang/thread$ vi thread2.c  
  2. fs@ubuntu:~/qiang/thread$ gcc -o thread2 thread2.c -lpthread  
  3. fs@ubuntu:~/qiang/thread$ ./thread2  
  4. Create parameter is 4  
  5. Pthread_create is created..  
  6. fs@ubuntu:~/qiang/thread$   

例程总结:
    可以看出来,我们在main函数中传递的整行指针,传递到我们新建的线程函数中。

在上面的例子可以看出来我们向新的线程传入了另一个线程的int数据,线程之间还可以传递字符串或是更复杂的数据结构。
例程3:
程序功能:向新建的线程传递字符串
程序名称:pthread_string.c
代码如下:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3.   
  4. void *create(char *arg)  
  5. {  
  6.     char *str;  
  7.     str = arg;  
  8.     printf("The parameter passed from main is %s\n",str);  
  9.   
  10.     return (void *)0;  
  11. }  
  12.   
  13. int main()  
  14. {  
  15.     int error;  
  16.     pthread_t id1;  
  17.     char *str1 = "Hello ,xiaoqiang!";  
  18.     char *attr = str1;  
  19.     error = pthread_create(&id1, NULL, create, (void *)attr);  
  20.   
  21.     if(error != 0)  
  22.     {  
  23.         printf("This pthread is not created!\n");  
  24.         return -1;  
  25.     }  
  26.     sleep(1);  
  27.   
  28.     printf("pthread is created..\n");  
  29.     return 0;  
  30. }  

执行结果如下:

[cpp] view plain copy
  1. fs@ubuntu:~/qiang/thread$ ./thread3  
  2. The parameter passed from main is Hello ,xiaoqiang!  
  3. pthread is created..  
  4. fs@ubuntu:~/qiang/thread$   

例程总结:
可以看出来main函数中的字符串传入了新建的线程中。

例程4:
程序功能:向新建的线程传递字符串
程序名称:pthread_struct.c

代码如下:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <stdlib.h>  
  4.   
  5. struct menber  
  6. {  
  7.     int a;  
  8.     char *s;  
  9. };  
  10.   
  11. void *create(void *arg)  
  12. {  
  13.     struct menber *temp;  
  14.     temp = (struct menber *)arg;  
  15.     printf("menber->a = %d\n",temp->a);  
  16.     printf("menber->s = %s\n",temp->s);  
  17.   
  18.     return (void *)0;  
  19. }  
  20.   
  21. int main()  
  22. {  
  23.     int error;  
  24.     pthread_t id1;  
  25.     struct menber *p;  
  26.     p = (struct menber *)malloc(sizeof(struct menber));  
  27.     p->a = 1;  
  28.     p->s = "xiaoqiang!";  
  29.   
  30.     error = pthread_create(&id1,NULL,create,(void *)p);  
  31.   
  32.     if(error)  
  33.     {  
  34.         printf("pthread is not created!\n");  
  35.         return -1;  
  36.     }  
  37.     sleep(1);  
  38.     printf("pthread is created!\n");  
  39.   
  40.     free(p);  
  41.     p = NULL;  
  42.     return 0;  
  43. }  

执行结果如下:

[cpp] view plain copy
  1. fs@ubuntu:~/qiang/thread$ vi thread4.c  
  2. fs@ubuntu:~/qiang/thread$ gcc -o thread4 thread4.c -lpthread  
  3. fs@ubuntu:~/qiang/thread$ ./thread4  
  4. menber->a = 1  
  5. menber->s = xiaoqiang!  
  6. pthread is created!  
  7. fs@ubuntu:~/qiang/thread$   

例程总结:
    可以看出来main函数中的一个结构体传入了新建的线程中。
    线程包含了标识进程内执行环境必须的信息。他集成了进程中的所有信息都是对线程进行共享的,包括文本程序、程序的全局内存和堆内存、栈以及文件描述符

例程5:
程序目的:验证新建立的线程可以共享进程中的数据
程序名称:pthread_share.c

代码如下:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3.   
  4. static int a = 5;  
  5.   
  6. void *create(void *arg)  
  7. {  
  8.     printf("New pthread...\n");  
  9.     printf("a = %d\n",a);  
  10.   
  11.     return (void *)0;  
  12. }  
  13.   
  14. int main(int argc, const char *argv[])  
  15. {  
  16.     int error;  
  17.     pthread_t id1;  
  18.   
  19.     error = pthread_create(&id1, NULL, create, NULL);  
  20.     if(error != 0)  
  21.     {  
  22.         printf("new thread is not created!\n");  
  23.         return -1;  
  24.     }  
  25.     sleep(1);  
  26.     printf("New thread is created...\n");  
  27.   
  28.     return 0;  
  29. }  

结果如下:

[cpp] view plain copy
  1. fs@ubuntu:~/qiang/thread$ vi thread5.c  
  2. fs@ubuntu:~/qiang/thread$ gcc -o thread5 thread5.c -lpthread  
  3. fs@ubuntu:~/qiang/thread$ ./thread5  
  4. New pthread...  
  5. a = 5  
  6. New thread is created...  
  7. fs@ubuntu:~/qiang/thread$   

例程总结:
可以看出来,我们在主线程更改了我们的全局变量a的值的时候,我们新建立的线程则打印出来了改变的值,可以看出可以访问线程所在进程中的数据信息。

2、线程的终止
如果进程中任何一个线程中调用exit,_Exit,或者是_exit,那么整个进程就会终止,
与此类似,如果信号的默认的动作是终止进程,那么,把该信号发送到线程会终止进程。
线程的正常退出的方式:
(1) 线程只是从启动例程中返回,返回值是线程中的退出码
(2) 线程可以被另一个进程进行终止
(3) 线程自己调用pthread_exit函数

两个重要的函数原型:

[cpp] view plain copy
  1. include <pthread.h>  
  2. void pthread_exit(void *rval_ptr);  
  3. /*rval_ptr 线程退出返回的指针*/  
  4.   
  5. int pthread_join(pthread_t thread,void **rval_ptr);  
  6.    /*成功结束进程为0,否则为错误编码*/  
pthread_join使一个线程等待另一个线程结束。
代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。
头文件 : #include <pthread.h>
函数定义: int pthread_join(pthread_t thread, void **retval);
描述 :pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
参数 :thread: 线程标识符,即线程ID,标识唯一线程。retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。 失败,返回的则是错误号。

 

例程6
程序目的:线程正常退出,接受线程退出的返回码
程序名称:pthread_exit.c
执行代码如下:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <unistd.h>  
  4.   
  5. void *create(void *arg)  
  6. {  
  7.     printf("new thread is created ... \n");  
  8.     return (void *)0;  
  9. }  
  10.   
  11. int main(int argc,char *argv[])  
  12. {  
  13.     pthread_t tid;  
  14.     int error;  
  15.     void *temp;  
  16.   
  17.     error = pthread_create(&tid, NULL, create, NULL);  
  18.   
  19.     if( error )  
  20.     {  
  21.         printf("thread is not created ... \n");  
  22.         return -1;  
  23.     }  
  24.     error = pthread_join(tid, &temp);  
  25.   
  26.     if( error )  
  27.     {  
  28.         printf("thread is not exit ... \n");  
  29.         return -2;  
  30.     }  
  31.   
  32.     printf("thread is exit code %d \n", (int )temp);  
  33.                                           
  34.     return 0;  
  35. }  

执行结果如下:

[cpp] view plain copy
  1. fs@ubuntu:~/qiang/thread$ vi thread6.c  
  2. fs@ubuntu:~/qiang/thread$ gcc -o thread6 thread6.c -lpthread  
  3. fs@ubuntu:~/qiang/thread$ ./thread6  
  4. new thread is created ...   
  5. thread is exit code 0   
  6. fs@ubuntu:~/qiang/thread$   

例程总结:
可以看出来,线程退出可以返回线程的int数值。

线程退出不仅仅可以返回线程的int数值,还可以返回一个复杂的数据结构

例程7
程序目的:线程结束返回一个复杂的数据结构
代码如下:
[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <unistd.h>  
  4.   
  5. struct menber  
  6. {  
  7.     int a;  
  8.     char *b;  
  9. }temp={8,"xiaoqiang"};  
  10.   
  11. void *create(void *arg)  
  12. {  
  13.     printf("new thread ... \n");  
  14.     return (void *)&temp;  
  15. }  
  16.   
  17. int main(int argc,char *argv[])  
  18. {  
  19.     int error;  
  20.     pthread_t tid;  
  21.     struct menber *c;  
  22.   
  23.     error = pthread_create(&tid, NULL, create, NULL);  
  24.   
  25.     if( error )  
  26.     {  
  27.         printf("new thread is not created ... \n");  
  28.         return -1;  
  29.     }  
  30.     printf("main ... \n");  
  31.   
  32.     error = pthread_join(tid,(void *)&c);  
  33.   
  34.     if( error )  
  35.     {  
  36.         printf("new thread is not exit ... \n");  
  37.         return -2;  
  38.     }  
  39.     printf("c->a = %d  \n",c->a);  
  40.     printf("c->b = %s  \n",c->b);  
  41.     sleep(1);  
  42.     return 0;  
  43. }  
执行结果如下:
[cpp] view plain copy
  1. fs@ubuntu:~/qiang/thread$ gcc -o thread7 thread7.c -lpthread  
  2. fs@ubuntu:~/qiang/thread$ ./thread7  
  3. main ...   
  4. new thread ...   
  5. c->a = 8    
  6. c->b = xiaoqiang    
  7. fs@ubuntu:~/qiang/thread$   
例程总结:
一定要记得返回的数据结构要是在这个数据要返回的结构没有释放的时候应用,如果数据结构已经发生变化,那返回的就不会是我们所需要的,而是脏数据。
 
3、线程标识
      函数原型:
#include <pthread.h>
pthread_t pthread_self(void);
pid_t getpid(void);
    getpid()用来取得目前进程的进程识别码,函数说明

例程8
程序目的:实现在新建立的线程中打印该线程的id和进程id
代码如下:
[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <unistd.h> /*getpid()*/  
  4.   
  5. void *create(void *arg)  
  6. {  
  7.     printf("New thread .... \n");  
  8.     printf("This thread's id is %u  \n", (unsigned int)pthread_self());  
  9.     printf("The process pid is %d  \n",getpid());  
  10.     return (void *)0;  
  11. }  
  12.   
  13. int main(int argc,char *argv[])  
  14. {  
  15.     pthread_t tid;  
  16.     int error;  
  17.   
  18.     printf("Main thread is starting ... \n");  
  19.   
  20.     error = pthread_create(&tid, NULL, create, NULL);  
  21.   
  22.     if(error)  
  23.     {  
  24.         printf("thread is not created ... \n");  
  25.         return -1;  
  26.     }  
  27.     printf("The main process's pid is %d  \n",getpid());  
  28.     sleep(1);  
  29.     return 0;  
  30. }  
  31. <span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"></span>  
执行结果如下:
[cpp] view plain copy
  1. fs@ubuntu:~/qiang/thread$ gcc -o thread8 thread8.c -lpthread  
  2. fs@ubuntu:~/qiang/thread$ ./thread8  
  3. Main thread is starting ...   
  4. The main process's pid is 4955    
  5. New thread ....   
  6. This thread's id is 3075853120    
  7. The process pid is 4955    
  8. fs@ubuntu:~/qiang/thread$  
0 0
原创粉丝点击