*author : Davidlin *date : 2014-12-20pm *email : [email protected] or [email protected] * 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 are 9527, I see you say:) */#define IS_MSG (MSG) ((msg->head) = = () && ((msg->tail) = =)) #defin E is_42 do {printf ("The Answer to the Ultimate Question of Life," "The Universe and Everything are 42\n"); }while (0) #define Init_msg_packet (MSG) {. Head = up,. Address = xx,. OpCode = 01, . length = xx,. Tail =,} #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 MS g_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);p thread_cond_t had_tx = Pthread_cond_initiali zer;pthread_mutex_t lock = pthreas_mutex_initializer;char msg_pack (char opcode); char msg_unpack (struct msg_pack ET *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);p rintf ("\n\t wait msg\n");p thread_cond_wait (&had_tx, &lock); Msg_unpack (&msg); Msg_info (&msg);p Thread_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); MS G_pack (Msg.opcode);p thread_mutex_unlock (&lock);p thread_cond_signal (&HAD_TX);p rintf (msg tx!\n); Sleep ( Rand ()%10);}} int main (int argc, char *argv[]) {pthread_t tid_tx;pthread_t Tid_rx;srand (Time (NULL));p thread_create (&tid_tx, NULL , THREAD_TX, NULL);p thread_create (&TID_RX, NULL, THREAD_RX, NULL);p Thread_join (tid_tx, NULL);p thread_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;}
Protocol: How to implement one of the simplest communication protocols (threading simulation)