/* *Author : DavidLin *Date : 2014-12-20pm *Email : linpeng1577@163.com or linpeng1577@gmail.com *world : the city of SZ, in China *Ver : 000.000.001 *For : threads for rxtx! *history : editor time do * 1)LinPeng 2014-12-20 created this file! * 2) */ #include<stdio.h> #include<stdlib.h> #include<pthread.h> struct msg_packet_t { char head; char address; char opcode; char length; char tail; }; /* Who is 9527, I see you say :) */ #define is_msg(msg) \ (((msg->head) == 95) && ((msg->tail) == 27))) #define IS_42 do \ { \ printf("The Answer to the Ultimate Question of Life," \ "The Universe and Everything is 42\n"); \ }while(0) #define INIT_MSG_PACKET(msg) \ { \ .head = 95, \ .address = 00, \ .opcode = 01, \ .length = 00, \ .tail = 27, \ } #define msg_info(msg) do \ { \ printf("\t %s. \n"\ "\t head :%d\n"\ "\t address :%d\n"\ "\t opcode :%d\n"\ "\t length :%d\n"\ "\t tail :%d\n"\ , \ __FUNCTION__,\ ((struct msg_packet_t*)msg)->head ,\ ((struct msg_packet_t*)msg)->address,\ ((struct msg_packet_t*)msg)->opcode ,\ ((struct msg_packet_t*)msg)->length ,\ ((struct msg_packet_t*)msg)->tail \ ); \ }while(0) struct msg_packet_t g_pool = INIT_MSG_PACKET(g_pool); pthread_cond_t had_tx = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAS_MUTEX_INITIALIZER; char msg_pack(char opcode); char msg_unpack(struct msg_packet *msg); void phy_tx(void* buff); void phy_rx(void* buff); void *thread_rx (void* buff) { struct msg_packet_t msg; pthread_mutex_lock(lock); printf("\n\t wait msg\n"); pthread_cond_wait(&had_tx, &lock); msg_unpack(&msg); msg_info(&msg); pthread_mutex_unlock(&lock); sleep(rand()%1); } void *thread_tx (void *buff) { struct msg_packet_t msg; while(1) { msg.opcode = rand()%43; pthread_mutex_lock(&lock); msg_pack(msg.opcode); pthread_mutex_unlock(&lock); pthread_cond_signal(&had_tx); printf(msg tx !\n); sleep(rand()%10); } } int main(int argc, char *argv[]) { pthread_t tid_tx; pthread_t tid_rx; srand(time(NULL)); pthread_create(&tid_tx, NULL, thread_tx, NULL); pthread_create(&tid_rx, NULL, thread_rx, NULL); pthread_join(tid_tx, NULL); pthread_join(tid_rx, NULL); exit(0); } char msg_unpack(struct msg_packet_t* msg) { phy_rx(msg); if(!IS_msg(msg)) { return; } switch(msg->opcode) { case 42: is_42; break; default: break; } } char msg_pack(char opcode) { struct msg_packet_t* ptr = &g_pool; ptr->opcode = opcode; phy_tx(&g_pool); } void phy_tx(void* buff) { g_pool = *(struct msg_packet_t*)buff; //phy tx } void phy_rx(void* buff) { //phy rx *(struct msg_packet_t*)buff = g_pool; }
协议实现:如何实现一个最简单的通信协议(线程模拟)
原创
©著作权归作者所有:来自51CTO博客作者linpeng1577的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
如何读懂通信协议?
进入通信行业,你会发现,无论在哪个岗位,都绕不开“协议”。前辈大牛们不
java 人工智能 linux python 大数据 -
通信协议栈拒绝服务python实现方式 通信协议栈开发
2021SC@SDUSC1. 核心组件 EventLoop 和 EventLoopGroup(已分析) Cha
通信协议栈拒绝服务python实现方式 netty HTTP 文件服务器 服务器