Linux Socket + pthread + pipe 实现socket通信和多线程数据共享

Linux Socket + pthread + pipe 实现socket通信和多线程数据共享大道至简,基础的东西不能忘,对于网路时代,开发应该都跑不了socket,作为一个基本功,也好久没写写,简单了一个复习下。主要目标复习下socket的同时,复习下linux多线程处理涉及知识点:1,socket2,linux pthread使用3,信号量(semaphore)、锁(mutex)、管道(pipe)、条件更多知识点,百度应该比较多了。代码逻辑:1,server:最大支持10个链接,当收到
摘要由CSDN通过智能技术生成

Linux Socket + pthread + pipe 实现socket通信和多线程数据共享

大道至简,基础的东西不能忘,对于网路时代,开发应该都跑不了socket,作为一个基本功,也好久没写写,简单了一个复习下。主要目标复习下socket的同时,复习下linux多线程处理
涉及知识点:
1,socket
2,linux pthread使用
3,信号量(semaphore)、锁(mutex)、管道(pipe)、条件
更多知识点,百度应该比较多了。
代码逻辑:
1,server:最大支持10个链接,当收到有效连接时启动一个线程用于处理对于事务(recvfromClient)
在线程中如果收到client发送字符串vote则触发另一个线程votepthread来通知(voteAction)policethread线程vote事件发生了(policeCenter)
2,client:相对简单就是支持循环输入
话不多说,代码如下:
server代码:

#include <iostream>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
using namespace std;
sem_t sem;
pthread_cond_t cond;
pthread_mutex_t mutex;
int pipeHandle[2];
void *voteAction(void *data) {
   
  while(1) {
   
    pthread_cond_wait(&cond, &mutex);
    pthread_t pid = pthread_self();
    cout <<"people "<< pid <<" vote action happen, please call 911" << endl;
    write(pipeHandle[1], &pid, sizeof(pthread_t));
    sem_post(&sem);
  }
  return NULL;
}

void *policeCenter(void* data) {
   
  while(1) {
   
    sem_wait(&sem);
    pthread_t senderId;
    read(pipeHandle[0],&senderId, sizeof(pthread_t));
    cout << "911 center recevice people "
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值