多线程优点

  使用线程的理由之一:

  和进程相比,它是一种“节俭”的多任务操作方式。在linux系统下,启动一个新的进程必须分配给他独立的地址空间,建立众多的数据表来维护它的代码段、堆栈段和数据段,这是一种“昂贵的”多任务工作方式。

运行于一个进程中的多个线程,他们之间使用相同的地址空间,而且线程间彼此切换所用的时间也远远小于进程间切换所用的时间。据统计,一个进程的开销大约是一个线程开销的30倍左右。

  使用多线程理由之二:

  线程间方便的通信机制。对不同进程来说,他们具有独立的数据空间,要进行数据传递只能通过进程间通信的方式进行,这种方式不仅耗时而且很不方便。线程则不然,由于同一进程下的线程之间共享数据空间,所以一个线程的数据可以直接为其它线程所用,这不仅快捷,而且方便。

  除了以上优点之外,多线程作为一种多任务、并发的工作方式,有如下优点:

  使多CPU系统更加有效,操作系统会保证当线程数不大于CPU数目时,不同的线程运行在不同的CPU上。

  改善程序结构。一个既长又复杂的进程可以考虑分为多个线程,成为几个独立或者半独立的部分,这样的程序会有利于理解和修改。

 

创建线程

 

#include<pthread.h>
int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,void *(*start_rtn)(void),void arg)

 

  • tidp:线程ID
  • attr:线程属性(通常为空)
  • start_rtn:线程要执行的函数
  • arg:start_rtn的参数

 

编译

  因为pthread的库不是LINUX系统库,所以在编译的时候要加上  -lphread

#gcc filename -lphread -o 。。。

  

线程实例之pthread_join()

 1 /********************************************************** 
 2 *程序要求:   在程序中创建一个线程,进程需等待该线程执行结束后才能继续执行。 
 3 *功能描述:   通过pthread_join阻塞等待,直至相应线程结束。 
 4 **********************************************************/  
 5 #include <unistd.h>  
 6 #include <stdio.h>  
 7 #include <pthread.h>  
 8   
 9 /* 
10 * 线程的执行函数 
11 * */  
12 void *thread(void *str)  
13 {  
14     int i;  
15     for (i = 0; i < 3; ++i)  
16     {  
17         sleep(2);  
18         printf( "This in the thread : %d\n" , i );  
19     }  
20     return NULL;  
21 }  
22   
23   
24 /* 
25 * 程序入口 
26 * */  
27 int main()  
28 {  
29     pthread_t pth;  
30     int i;  
31   
32     /*创建线程并执行线程执行函数*/  
33     int ret = pthread_create(&pth, NULL, thread, NULL);    
34     printf("The main process will be to run,but will be blocked soon\n");     
35     /*阻塞等待线程退出*/  
36     pthread_join(pth, NULL);  
37   
38     printf("thread was exit\n");  
39     for (i = 0; i < 3; ++i)  
40     {  
41         sleep(1);  
42         printf( "This in the main : %d\n" , i );  
43     }  
44     return 0;  
45 }  
View Code

相关文章:

  • 2021-12-15
  • 2021-04-15
  • 2021-06-29
  • 2021-05-28
  • 2022-12-23
  • 2021-07-28
  • 2021-06-10
  • 2022-12-23
猜你喜欢
  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
  • 2022-02-12
  • 2021-12-01
  • 2021-12-21
  • 2022-12-23
相关资源
相似解决方案