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 "