【C语言】多进程/多线程

news/2025/3/30 2:53:27/

【C语言】多进程/多线程

  • 参考链接
  • 多进程/多线程服务器
    • 1. 多进程服务器
    • 2. 多线程服务器
  • 结语
  • 参考链接

在这里插入图片描述

参考链接

c 中文网
菜鸟 c

多进程/多线程服务器

  多进程和多线程是常用的并发编程技术。它们都允许程序同时执行多个任务,提高了系统的资源利用率和程序的运行效率。

1. 多进程服务器

  多进程是指在操作系统中同时运行多个独立的进程。每个进程都有自己独立的地址空间和资源,进程间的通信通过操作系统提供的进程间通信机制进行。多进程可以充分利用多核处理器的优势,提高系统的整体性能。然而,进程间的切换会引入较大的开销,并且需要较高的内存开销。

  服务器使用 fork 创建子进程来和客户端进行通信,父进程负责取出连接请求。

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <strings.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <arpa/inet.h>// 信号处理函数
void waitchild(int signo)
{pid_t wpid;while (1){wpid = waitpid(-1, NULL, WNOHANG);if (wpid > 0){printf("child exit, wpid==[%d]\n", wpid);}else if (wpid == 0 || wpid == -1){break;}}
}int main()
{// 阻塞SIGCHLD信号sigset_t mask;sigemptyset(&mask);sigaddset(&mask, SIGCHLD);sigprocmask(SIG_BLOCK, &mask, NULL);int sigbol = 1;int sfd = socket(AF_INET, SOCK_STREAM, 0);// 设置端口复用int opt = 1;setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));struct sockaddr_in soaddr;bzero(&soaddr, sizeof(soaddr));soaddr.sin_family = AF_INET;soaddr.sin_port = htons(9999);soaddr.sin_addr.s_addr = htonl(INADDR_ANY);bind(sfd, (struct sockaddr *)&soaddr, sizeof(soaddr));//监听-listenlisten(sfd, 128);struct sockaddr_in clientsocket;socklen_t clilen;char sIP[16];while (1){clilen = sizeof(clientsocket);bzero(&clientsocket, clilen);int cfd = accept(sfd, (struct sockaddr *)&clientsocket, &clilen);/* */int pid = fork();if (pid == 0){// 子进程close(sfd);char buff[64];printf("current pid is [%d],father is [%d]\n", getpid(), getppid());while (1){memset(buff, 0x00, sizeof(buff));int n = read(cfd, buff, sizeof(buff));if (n == 0){return 0;}else if (n < 0){perror("child read error");return -1;}printf("child [%d] recv data from [%s:%d]:[%s]\n", getpid(), inet_ntop(AF_INET, &clientsocket.sin_addr.s_addr, sIP, sizeof(sIP)), ntohs(clientsocket.sin_port), buff);for (int i = 0; i < n; i++){buff[i] = toupper(buff[i]);}n = Write(cfd, buff, n);if (n <= 0){perror("child write error");return -1;}}}else if (pid > 0){// 父进程close(cfd);//假如是初次fork子进程,那么才注册信号处理函数if (sigbol == 1){sigbol = 0;// 注册SIGCHLD信号处理函数struct sigaction act;act.sa_handler = waitchild;act.sa_flags = 0;sigemptyset(&act.sa_mask);sigaction(SIGCHLD, &act, NULL);// 解除对SIGCHLD信号的阻塞sigprocmask(SIG_UNBLOCK, &mask, NULL);}//循环等待下一个连接请求的到来continue;}else{perror("fork error");close(sfd);return -1;}}return 0;
}

2. 多线程服务器

  多线程是指在同一个进程中同时运行多个独立的线程。与进程不同,线程共享同一个地址空间和资源,可以通过共享内存等方式进行线程间的通信。多线程可以减少线程间的切换开销和内存开销,提高系统的响应速度和资源利用率。然而,多线程编程需要考虑线程安全问题,需要使用线程同步技术来保证共享资源的正确访问。

  主线程创建子线程,用子进程和客户端通信。

#include <arpa/inet.h>
#include <pthread.h>
#include <strings.h>
#include <string.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <unistd.h>typedef struct info
{int cfd; // 若为-1表示可用, 大于0表示已被占用int idx;pthread_t thread;          // 由pthread_create 返回struct sockaddr_in client; // 由accept 返回
} INFO;INFO thInfo[1024];void initThreadArr()
{for (int i = 0; i < 1024; i++){bzero(&thInfo[i],sizeof(thInfo[i]));thInfo[i].cfd = -1;}
}int findIndex()
{int i;for (i = 0; i < 1024; i++){if (thInfo[i].cfd == -1){return i;}}//if (i == 1024)//{//    return -1;//}return -1;
}void *threadFunc(void *arg)
{INFO *curthread = (INFO *)arg;char sIP[16];printf("current thread id [%ld],arr index is [%d],cfd is [%d],client ip is [%s:%d]\n", pthread_self(), curthread->idx, curthread->cfd, inet_ntop(AF_INET, &curthread->client.sin_addr.s_addr, sIP, sizeof(sIP)), ntohs(curthread->client.sin_port));char buff[64];while (1){memset(buff, 0x00, sizeof(buff));int n = read(curthread->cfd, buff, sizeof(buff));if (n == 0){bzero(&thInfo[curthread->idx],sizeof(thInfo[curthread->idx]));thInfo[thInfo->idx].cfd = -1;return 0;}else if (n < 0){bzero(&thInfo[curthread->idx],sizeof(thInfo[curthread->idx]));thInfo[thInfo->idx].cfd = -1;perror("child read error");return 0;}printf("child thread [%ld] recv data from [%s:%d]:[%s]\n", pthread_self(), inet_ntop(AF_INET, &curthread->client.sin_addr.s_addr, sIP, sizeof(sIP)), ntohs(curthread->client.sin_port), buff);for (int i = 0; i < n; i++){buff[i] = toupper(buff[i]);}n = write(curthread->cfd, buff, n);if (n <= 0){bzero(&thInfo[curthread->idx],sizeof(thInfo[curthread->idx]));thInfo[thInfo->idx].cfd = -1;perror("child write error");return 0;}}
}int main()
{initThreadArr();int sfd = socket(AF_INET, SOCK_STREAM, 0);// 设置端口复用int opt = 1;setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));struct sockaddr_in soaddr;bzero(&soaddr, sizeof(soaddr));soaddr.sin_family = AF_INET;soaddr.sin_port = htons(9999);soaddr.sin_addr.s_addr = htonl(INADDR_ANY);bind(sfd, (struct sockaddr *)&soaddr, sizeof(soaddr));// 监听-listenlisten(sfd, 128);struct sockaddr_in clientsocket;socklen_t clilen;int cfd;int index;int ret;while (1){index = -1;clilen = sizeof(clientsocket);bzero(&clientsocket, clilen);cfd = accept(sfd, (struct sockaddr *)&clientsocket, &clilen);// 从线程数组中找一个可以用的index = findIndex();thInfo[index].idx = index;thInfo[index].client = clientsocket;thInfo[index].cfd = cfd;// 创建线程ret = pthread_create(&thInfo[index].thread, NULL, threadFunc, &thInfo[index]);if (ret != 0){printf("create thread error:[%s]\n", strerror(ret));exit(-1);}// 设置子线程为分离属性pthread_detach(thInfo[index].thread);}Close(sfd);return 0;
}

结语

  多进程和多线程的选择取决于具体的应用场景。如果任务之间需要较高的隔离度,或者需要充分利用多核处理器的优势,可以选择多进程。如果任务之间需要较低的切换开销和内存开销,或者需要提高系统的响应速度和资源利用率,可以选择多线程。

参考链接

c 中文网
菜鸟 c

文章来源:https://blog.csdn.net/qq_44653106/article/details/146434643
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ppmy.cn/news/1583231.html

相关文章

git-lfs: command not found

遇到 git-lfs: command not found 错误&#xff0c;表示你的系统中未安装 Git Large File Storage (LFS) 扩展工具。以下是针对不同操作系统的解决方案&#xff1a; 1. 安装 Git LFS 根据你的操作系统选择安装方式&#xff1a; macOS 使用 Homebrew&#xff08;推荐&#xff…

MATLAB 中,并行池(Parallel Pool)自动关闭的情况

在 MATLAB 中&#xff0c;并行池&#xff08;Parallel Pool&#xff09;的行为可以通过设置进行控制&#xff0c;但默认情况下&#xff0c;并行池不会自动关闭&#xff0c;除非满足某些条件或显式调用关闭命令。以下是关于并行池自动关闭机制的详细说明&#xff1a; 自动关闭的…

19926 分球

19926 分球 ⭐️考点&#xff1a;数学、排列组合 &#x1f31f;难度&#xff1a;简单 &#x1f4d6; &#x1f4da; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner;public class Main {static long[][] dp ne…

盛铂科技SPP5006/18/40G峰值脉冲功率计探头 国产功率计

功率计简述 SPP5000系列是盛铂科技自主开发的自带USB 接口的多功能便携式数字脉冲峰值功率计&#xff0c;可快速执行50MHz至40GHz频率范围和-20dBm至20dBm动态范围的设置和测量&#xff0c;SPP5000系列具备脉冲信号测量与连续波信号测量能力。系统内置等效24Bit 高速采样ADC 并…

小程序跳转到h5页面

本组件使用useState、WebView、Taro的钩子&#xff0c;以及taro-hooks中的useRouter。组件内部使用了useRouter获取路由信息&#xff0c;从存储中获取openId和TOKEN&#xff0c;然后通过useReady生命周期钩子设置URL。分享功能部分使用useShareAppMessage处理&#xff0c;构建分…

关于CNN,RNN,GAN,GNN,DQN,Transformer,LSTM,DBN你了解多少

以下是神经网络中常见的几种模型的简要介绍&#xff1a; 1. ​CNN (Convolutional Neural Network, 卷积神经网络) ​用途: 主要用于图像处理和计算机视觉任务。​特点: 通过卷积核提取局部特征&#xff0c;具有平移不变性&#xff0c;能够有效处理高维数据&#xff08;如图像…

智能汽车图像及视频处理方案,支持视频实时拍摄特效能力

在智能汽车日新月异的今天&#xff0c;美摄科技作为智能汽车图像及视频处理领域的先行者&#xff0c;凭借其卓越的技术实力和前瞻性的设计理念&#xff0c;为全球智能汽车制造商带来了一场视觉盛宴的革新。美摄科技推出智能汽车图像及视频处理方案&#xff0c;一个集高效性、智…

The First项目报告:Layer 2 时代的先锋Epic Chain

随着区块链行业的不断演进&#xff0c;新兴公链项目不断涌现&#xff0c;推动整个生态体系向更高效、更安全、更智能的方向发展。Epic Chain作为一条创新型区块链&#xff0c;以高性能架构、跨链兼容性和去中心化金融&#xff08;DeFi&#xff09;生态为核心&#xff0c;正迅速…