gpt4 book ai didi

c - 如何从一个线程向另一个线程发送消息(用C语言编写)?

转载 作者:行者123 更新时间:2023-12-03 12:52:13 26 4
gpt4 key购买 nike

我正在尝试从一个线程向另一个线程发送消息。每个线程都知道另一个线程的线程ID。如何在他们之间发送消息?

我已经看到了一些建议的解决方案(消息队列,匿名管道等),但老实说,我没有让它们起作用。显然,我对前面的描述不够了解,因此是本主题。

综上所述,这只是最短的发送方式,我们假设一条消息“Hello!”。从一个线程转移到另一个线程,使第二个线程在stderr上显示它,然后发送回第一个线程消息“Hello back!”。

这可能很容易,而且我的研究工作做得不好,但是我已经呆了一段时间了,找不到合适的方法来做。

最佳答案

一个例子很简单-首先使用pipe()制作管道。 It creates two file descriptor —一个用于阅读,第二个用于写作。在这里,我们两次调用它来兼顾读取和写入。然后,我们调用fork(创建第二个线程),并通过创建的管道写入/读取消息。

#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int wait_n_read(int fd, char* buf, int szBuf) {
struct pollfd pfd = {
.fd = fd,
.events = POLLIN,
.revents = 0
};
poll(&pfd, 1, -1); //wait for an event
int ret = read(fd, buf, szBuf);
if (ret == -1) {
perror("In read()");
}
return ret;
}

main(){
int chan[4];
enum{
thread1_read = 0, //read end for parent
thread2_write = 1, //write end for child
thread2_read = 2, //read end for child
thread1_write = 3 //write end for parent
};
if (pipe(&chan[thread1_read]) == -1 || (pipe(&chan[thread2_read]) == -1)){
perror("In pipe");
return 1;
}
switch(fork()) {
case -1:
perror("In fork()");
return 1;
case 0:{ //it's a child
char buf[256];
memset(buf, 0, sizeof(buf));
if (wait_n_read(chan[thread2_read], buf, sizeof(buf)-1) == -1)
return 1;
fputs(buf, stderr);
const char helloback[] = "Hello back\n";
write(chan[thread2_write], helloback, sizeof(helloback));
return 0;
}
default: { //a parent
const char hello[] = "Hello\n";
write(chan[thread1_write], hello, sizeof(hello));
char buf[256];
memset(buf, 0, sizeof(buf));
if (wait_n_read(chan[thread1_read], buf, sizeof(buf-1)) == -1)
return 1;
fputs(buf, stderr);
}
}
}

关于c - 如何从一个线程向另一个线程发送消息(用C语言编写)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30823317/

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