/*
*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;
}
转载于:https://blog.51cto.com/linpeng/1596725