如何将消息(在 C 中)从一个线程发送到另一个线程?

How to send message (in C) from one thread to another?

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

我已经看到了一些建议的解决方案(消息队列、匿名管道等),但老实说我没有让它们起作用。显然我对前面的描述理解不够,所以才有这个话题。

所以总结一下,这只是最短的发送方式,假设消息 "Hello!" 从线程到另一个线程,让第二个线程在 stderr 上显示它,然后发回给第一个线程消息'Hello back!'.

应该很容易,我没有好好研究,但我已经卡了一段时间了,找不到合适的方法。

举个例子,很简单——先用pipe()做一个管道。 It creates two file descriptor — 一个用于阅读,第二个用于写作。在这里,我们两次调用它以同时具有读取和写入端。然后我们通过我们创建的管道调用 fork (创建第二个线程) 和 write/read 消息。

#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);
        }
    }
}