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 "<< senderId <<" notify vote event happened"

本文介绍了如何在Linux环境下利用Socket、pthread和pipe实现socket通信及多线程间的数据共享。主要内容包括socket基础知识、pthread线程使用,以及信号量、锁和管道的运用。在服务器端,当接收到客户端的有效连接时,会创建新线程处理事务。若接收到特定字符串,将触发另一线程通知事件。客户端则负责循环输入。提供了server和client的代码示例。
最低0.47元/天 解锁文章
736

被折叠的 条评论
为什么被折叠?



