Я пытаюсь передать сообщения между двумя потоками, используя очередь, но пока не получил никаких результатов.Когда я печатаю содержимое сообщения после того, как оно получено и до того, как оно отправлено, кажется, что оно только сохраняет его значение в протекторе.Мне нужно реализовать это с 1 серверным потоком и несколькими клиентскими потоками, но сейчас я использую только 1 из каждого.Вот мой код
struct msg //struct for client requests to server
{
long mtype;
int numResources; //number of resources to be requested
int ID; //ID associated with client thread
};
int c1PID; //process ID variable for client thread 1
int serverPID;
key_t key1;
key_t keyS;
int msqid1;
int msqidS;
int main(int arc, char *argv[])
{
key1 = ftok(".", '1'); //queue for client thread 1 to receive msgs from server
msqid1 = msgget(key1, 666 | IPC_CREAT);
keyS = ftok(".", 's'); //general queue for server
msqidS = msgget(keyS, 666 | IPC_CREAT);
pthread_t threads[2]; //create an array of pthreads
if ((serverPID = pthread_create(&threads[0], NULL, server, NULL)) != 0)
{
perror("server thread");
exit(1);
}
if ((c1PID = pthread_create(&threads[1], NULL, client, NULL)) != 0)
{
perror("client thread");
exit(1);
}
pthread_exit(NULL);
}
void *server()
{
struct msg request;
size_t size = sizeof(struct msg) - offsetof(struct msg, numResources);
while (1)
{
msgrcv(msqidS, &request, size, 2, 0);
printf("received: numResources requested = %d\n", request.numResources);
request.numResources = 9001;
printf("sending: numResources requested = %d\n", request.numResources);
msgsnd(msqid1, &request, size, 0);
sleep(1);
}
}
void *client()
{
struct msg request;
size_t size;
request.numResources = 0;
size = sizeof(struct msg) - offsetof(struct msg, numResources);
msgsnd(msqidS, &request, size, 0);
while(1)
{
msgrcv(msqid1, &request, size, 2, 0);
printf("received: numResources requested = %d\n", request.numResources);
request.numResources += 1;//(int)(ceil((double)(rand()%2)) + 1);
printf("sending: numResources requested = %d\n", request.numResources);
msgsnd(msqidS, &request, size, 0);
sleep(1);
}
Я вынул много своих заявлений на печать, но это выглядит примерно так:
Server thread:
received: numResources = 9001;
sending: numResources = 9001;
client thread:
received: numResources = 1;
sending: numResources = 2;
Server thread:
received: numResources = 9001;
sending: numResources = 9001;
client thread:
received: numResources = 2;
sending: numResources = 3;