我想使用一个队列在2个线程之间传递消息,但到目前为止我还没有得到任何结果。当我收到消息并在发送消息之前打印消息的内容时,它似乎只是保持其值。我需要用1个服务器线程和多个客户端线程来实现它,但现在我只使用每个线程中的一个。这里是我的代码C - 在使用队列的线程之间传递消息的问题
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);
}
我拿出我的很多的print语句,但它看起来是这样的:
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;
您是否试图实现一个客户端服务器程序,它将在两台独立的机器上运行,或者您将只有两个线程相互通信? – JonVD 2010-11-15 01:31:55
他们只是在同一台机器上互相交谈 – Anon 2010-11-15 01:34:34