00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032 # include <pthread.h>
00033 # include <stdio.h>
00034 # include <string.h>
00035 # include <unistd.h>
00036
00037 # include "MsgQLib.h"
00038
00039 ULONG q1 = 1;
00040 ULONG q2 = 2;
00041 const int KMaxMsg = 10;
00042
00047 void ThreadFunction(int *id) {
00048 int i = 2;
00049 int err = 0;
00050 int result = 0;
00051 int pri = MSG_PRI_NORMAL;
00052 int timeout = NO_WAIT;
00053 int len = 100;
00054 int nBytes;
00055 char smsg[] = "Sending Some Data through MsgQ";
00056 char rmsg[100];
00057 ULONG queueOne = q1;
00058 ULONG queueTwo = q2;
00059
00060
00061 if(*id == q2) {
00062 queueOne = q2;
00063 queueTwo = q1;
00064 }
00065
00066 printf("Thread %d: Started..\n", *id);
00067
00068
00069
00070 result = MsgQCreate(queueOne, KMaxMsg, MSG_Q_FIFO, &err);
00071 printf("Thread %d: Q CREATE result = %d\n", *id, result);
00072
00073 while(i>=0) {
00074
00075 nBytes = strlen(smsg);
00076
00077 result = MsgQSend(queueOne, smsg, nBytes, pri, timeout, &err);
00078 printf("Thread %d: Q SEND result = %d\n", *id, result);
00079
00080 sleep(1);
00081 rmsg[0] = '\0';
00082
00083 result = MsgQReceive(queueTwo, rmsg, len, timeout, &err);
00084 rmsg[result] = '\0';
00085 printf("Thread %d: Q RECEIVE result = %d\n", *id, result);
00086 printf("Thread %d: Message Received from Message Queue 2 is : %s\n", *id, rmsg);
00087 i--;
00088 }
00089 sleep(2);
00090
00091
00092 result=MsgQDelete(queueOne, &err);
00093 printf("Thread %d: Q DELETE result = %d\n", *id, result);
00094 }
00095
00096
00097 int main() {
00098 int result;
00099 int err;
00100 pthread_t thread1;
00101 pthread_t thread2;
00102
00103 printf("Main Thread: Started..\n");
00104
00105
00106 result = MsgQCreate(q1, KMaxMsg, MSG_Q_FIFO, &err);
00107 printf("Main Thread: Q CREATE result = %d\n",result);
00108
00109 result = MsgQCreate(q2, KMaxMsg, MSG_Q_FIFO, &err);
00110 printf("Main Thread: Q CREATE result = %d\n",result);
00111
00112
00113
00114 if(pthread_create(&thread1, NULL, (thread_begin_routine)ThreadFunction, (void*) &q1) != 0) {
00115 printf("Main Thread: Failed to create the threadOne\n");
00116 }
00117
00118 if(pthread_create(&thread2, NULL, (thread_begin_routine)ThreadFunction, (void*) &q2) != 0) {
00119 printf("Main Thread: Failed to create the threadTwo\n");
00120 }
00121
00122
00123 pthread_join(thread1, NULL);
00124 pthread_join(thread2, NULL);
00125 printf("Main Thread: Exiting from Main() \nMain Thread: Enter a Key to Exit");
00126 getchar();
00127 return 0;
00128 }