gpt4 book ai didi

C - 使用队列在线程之间传递消息的问题

转载 作者:行者123 更新时间:2023-12-04 06:41:29 25 4
gpt4 key购买 nike

我正在尝试使用队列在 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;

最佳答案

编辑:
sizeof(struct msg) - offsetof(struct msg, numResources);应该可以。

但是,您的 mtype需要,根据 docs ,一个正整数。将其初始化为 2,因为您对 msgrecv 的调用表示仅接收消息类型 2。

向所有 msgsnd/msgrecv 调用添加错误检查,这样您就可以确定您不会默默地收到错误。

向您的 ftok 和 msgget 调用添加错误检查。

关于C - 使用队列在线程之间传递消息的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4180735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com