您好,欢迎来到汇智旅游网。
搜索
您的当前位置:首页socket网络编程实现并发服务器——多线程

socket网络编程实现并发服务器——多线程

来源:汇智旅游网

线程介绍

1,什么是线程

2,主线程和子线程

一个进程创建后,会首先生成一个缺省的线程,通常称这个线程为主线程(或称控制线程),C/C++程序中,主线程就是通过 main函数进入的线程,由主线程调用pthread_create()创建的线程称为子线程,子线程也可以有自己的入口函数,该函数由用户 在创建的时候指定。每个线程都有自己的线程ID,可以通过pthread_self()函数获取。

3,创建线程

函数原型:

#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *),  void *arg);
Compile and link with -pthread.

(说明: pthreand_create()用来创建一个线程,并执行第三个参数start_routine所指向的函数。)

第三个参数start_routine是一个函数指针,它指向的函数原型是 void *func(void *),这是所创建的子线程要执行的任务 (函数);
第四个参数arg就是传给了所调用的函数的参数,如果有多个参数需要传递给子线程则需要封装到一个结构体里传进去; 第一个参数thread是一个pthread_t类型的指针,他用来返回该线程的线程ID。每个线程都能够通过pthread_self()来获取 自己的线程ID(pthread_t类型)。
第二个参数是线程的属性,其类型是pthread_attr_t类型,其定义如下:

typedef struct
 {     
         int                               detachstate;   线程的分离状态     
         int                               schedpolicy; 线程调度策略      
         struct sched_param                schedparam;  线程的调度参数    
         int                               inheritsched;  线程的继承性   
         int                               scope;       线程的作用域    
         size_t                            guardsize;   线程栈末尾的警戒缓冲区大小   
         int                               stackaddr_set;   
         void *                            stackaddr;   线程栈的位置     
         size_t                            stacksize;线程栈的大笑
  }
   

代码示例:

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <getopt.h>
#include <pthread.h>
#include <ctype.h>

typedef void *(THREAD_BODY) (void *thread_arg); 
void *thread_worker(void *ctx);
//封装thread_start()函数,实现创建子线程的功能
int thread_start(pthread_t * thread_id, THREAD_BODY * thread_workbody, 

void *thread_arg);     //帮助信息
{
       printf("%s usage: \n", progname);     
       printf("-p(--port): sepcify server listen port.\n");             
       printf("-h(--Help): print this help information.\n");

      return}
int main(int argc, char **argv)
{
       int                  sockfd = -1; 
       int                  rv = -1;
       struct sockaddr_in   servaddr; 
       struct sockaddr_in   cliaddr;
       socklen_t            len; 
       int                  port = 0;   
       int                  clifd;  
       int                  ch;  
       int                  on = 1;   
       pthread_t            tid;    //定义线程
       struct option        opts[] = {  
                     {"port", required_argument, NULL, 'p'},                  
                     {"help", no_argument, NULL, 'h'},                
                     {NULL, 0, NULL, 0}        };
}

while( (ch=getopt_long(argc, argv, "p:h", opts, NULL)) != -1 )       
 {               
           switch(ch)                
           {              
                     case 'p':                                
                             port=atoi(optarg);                                
                             break;
                     case 'h':                                 
                             print_usage(argv[0]);                                
                             return 0;             
           }
 }

  if( !port )           //判断端口连接
 {               
                 print_usage(argv[0]);                
                 return 0;     
  }
   sockfd=socket(AF_INET, SOCK_STREAM, 0);      
   if(sockfd < 0)      
   {             
              printf("Create socket failure: %s\n", strerror(errno));                
              return -1;     
    }      
    printf("Create socket[%d] successfully!\n", sockfd);

    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    memset(&servaddr, 0, sizeof(servaddr));                 
    servaddr.sin_family=AF_INET;      
    servaddr.sin_port = htons(port);     
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY); /* 监听所有 */ 
    //inet_aton("127.0.0.1", &servaddr.sin_addr) ;/*监听某个ip*/

      rv=bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));        
      if(rv < 0)       
       {                
               printf("Socket[%d] bind on port[%d] failure: %s\n", sockfd, port, strerror(errno));               
                 return -2;       
       }
          listen(sockfd, 13);       
         printf("Start to listen on port [%d]\n", port);
 
        while(1)       
         {               
                       printf("Start accept new client incoming...\n");
                       clifd=accept(sockfd, (struct sockaddr *)&cliaddr, &len);               
                       
                       if(clifd < 0)          
                       {                
                               printf("Accept new client failure: %s\n", strerror(errno));                       
                                continue;               
                      }
                      printf("Accept new client[%s:%d] successfully\n"inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
                      thread_start(&tid, thread_worker, (void *)clifd);        }
                      close(sockfd);
                       return 0;
}

int thread_start(pthread_t * thread_id, THREAD_BODY * thread_workbody, void *thread_arg) 
{
          int                 rv = -1;      
          pthread_attr_t      thread_attr;

 //线程初始化
  if( pthread_attr_init(&thread_attr) )      
  {             
         printf("pthread_attr_init() failure: %s\n", strerror(errno));                      
         goto CleanUp;      
   }
   
  if( pthread_attr_setstacksize(&thread_attr, 120*1024) )        
  {               
          printf("pthread_attr_setstacksize() failure: %s\n", strerror(errno));                
          goto CleanUp;        
   }
   if( pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED) )        
   {
          printf("pthread_attr_setdetachstate() failure: %s\n", strerror(errno));                
          goto CleanUp;       
     }
        /*创建线程*/       
      if( pthread_create(thread_id, &thread_attr, thread_workbody, thread_arg) )        
      {                
                    printf("Create thread failure: %s\n", strerror(errno));                
                    goto CleanUp;     
       }
        rv = 0;                                                    CleanUp:             
          /* 用完之后摧毁线程 */                           
          pthread_attr_destroy(&thread_attr);     
          return rv; 
          }

void *thread_worker(void *ctx) 
{        
               int                  clifd;        
               int                  rv;        
               char                 buf[1024];        
               int                  i;
        
    if( !ctx )       
     {               
      printf("Invalid input arguments in %s()\n", __FUNCTION__);                pthread_exit(NULL);       
       }
    clifd = (int)ctx;
        printf("Child thread start to commuicate with socket client...\n");
       
     while(1)        
     {               
           memset(buf, 0, sizeof(buf));               
           rv=read(clifd, buf, sizeof(buf));                
       if( rv < 0)                
       {                        
              printf("Read data from client sockfd[%d] failure: %s and thread will exit\n", clifd, strerror(errno));                          
              close(clifd);                       
              pthread_exit(NULL);                
              }               
        else if( rv == 0)                
        {                       
         printf("Socket[%d] get disconnected and thread will exit.\n", clifd);                        
         close(clifd);                        
         pthread_exit(NULL);                
         }                
         else if( rv > 0 )                
         {                        
         printf("Read %d bytes data from Server: %s\n", rv, buf);                      
         }
                /* convert letter from lowercase to uppercase */                    
         for(i=0; i<rv; i++)                
         {                        
               buf[i]=toupper(buf[i]);                
         }                               
         rv=write(clifd, buf, rv);                
         if(rv < 0)                
         {                        
                       printf("Write to client by sockfd[%d] failure: %s and thread will exit\n", clifd, strerror(errno));
                        
                        close(clifd);                        
                        pthread_exit(NULL);              
            }        
        }
   }


保存后再linux下运行:

4,线程与进程的区别与联系

1,关于多进程和多线程,“进程是资源分配的最小单位,线程是CPU调度的最小单位”。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- hzar.cn 版权所有 赣ICP备2024042791号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务