【发布时间】:2011-05-10 00:09:16
【问题描述】:
我正在尝试使用队列在 2 个线程之间传递消息,但到目前为止我还没有得到任何结果。当我在收到消息之后和发送之前打印消息的内容时,它似乎只是将其价值保持在范围内。我需要用 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;
【问题讨论】:
-
您是在尝试实现一个客户端服务器程序,该程序将位于两台不同的机器上,还是只有两个线程相互通信?
-
他们只是在同一台机器上互相交谈
标签: c pthreads message-queue