简体   繁体   English

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

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

I'm trying to send a message from one thread to another.我正在尝试将消息从一个线程发送到另一个线程。 Each thread knows the thread ID of the other.每个线程都知道另一个线程的 ID。 How can I send a message between them?我如何在他们之间发送消息?

I've already seen some proposed solutions (message queue, anonymous pipe, etc.) but honestly I didn't get them to work.我已经看到了一些建议的解决方案(消息队列、匿名 pipe 等),但老实说我没有让它们工作。 Obviously I didn't understand the previous descriptions enough, hence this topic.显然我对前面的描述理解不够,所以这个话题。

So to sum up, just the shortest possible way to send, let's say a message "Hello," from thread to another thread, make the 2nd thread show it on stderr.总而言之,只是发送的最短方式,比如说一条消息“你好”,从线程到另一个线程,让第二个线程在 stderr 上显示它。 and than send back to 1st thread message 'Hello back!'.然后发回第一个线程消息“你好回来!”。

It's probably very easy and I didn't do a good job of researching, but I've been stuck for some time now, and can't find decent way to do this.这可能很容易,我没有做好研究工作,但我已经被困了一段时间,找不到合适的方法来做到这一点。

An example, it's pretty simple — first make a pipe with pipe() . 一个例子,很简单-首先使用pipe()创建一个管道。 It creates two file descriptor — one for reading, and the second for writing. 它创建两个文件描述符 -一个用于读取,另一个用于写入。 Here we calling it two times to have both read and write sides. 在这里,我们两次调用它来同时具有读写方面。 Then we calling fork (that makes a second thread) , and write/read messages through the pipes we created. 然后,我们调用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);
        }
    }
}

A little late to the party, but none of these answers, address the simple solution.聚会有点晚了,但这些答案都没有解决简单的解决方案。 Use globals and 1. Use a mutex.使用全局变量和 1. 使用互斥体。 2. Do not use a mutex, for shut-down-coming flags. 2. 不要使用互斥锁,用于关闭即将到来的标志。 3. (horrible, not portable, but works great) Do not use mutexs when claiming work for the thread using file rename() on aix/xlc. 3.(可怕,不可移植,但效果很好)在 aix/xlc 上使用文件 rename() 为线程声明工作时不要使用互斥锁。 Rename is automous, and will succed or fail.重命名是自动的,将成功或失败。 On success, your thread, has the work.成功后,你的线程就有了工作。 On failure, nope, another thread won.失败时,不,另一个线程赢了。 Port this solution to linux, and it will fail, misserably, because rename function is not automous for linux gcc.将此解决方案移植到 linux,它会失败,可悲的是,因为重命名 function 对于 ZE206A54E97690CCE50CC872ZDD70EE8964FZE203AF4.91365CBDDC41203AF4.ZE206A54E97690CCE50CC872ZDD70EE8964FZE872ZDD70EE8964FZE25268E68385D1AB5074C17A94F14Z 不是自动的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM