如何将线程连接到管道并将信息检索到另一个线程?

时间:2019-01-18 17:49:04

标签: c multithreading queue pipe

有4个输入(4个管道)和10个输出(10个管道)。 每个人必须与其他人同时阅读。每个输入管道均会接收用于标识容器的字符串(该程序可重新创建仓库中对容器的处理,然后将其运送至10个目的地之一),这些字符串还包含序列号和目的地。

字符串必须由每个管道处理。然后将它们放入一个队列中(在处理之前,它们必须在该队列中停留1秒钟)。然后将它们发送到维度[n] [n]的矩阵中,等待1到5秒,然后根据目的地将其定向到10个输出队列之一(例如,伦敦):“ LND”。

为矩阵中的每个容器创建一个线程,该线程等待之前提到的1到5秒钟,然后将其放入输出队列。每个队列都有一个专用线程进行处理,并等待2秒钟,然后将其写入输出管道之一。

我不明白如何连接每个部分(线程到管道,然后到队列等)。

我们尝试了多种方法将线程连接到管道,并在文件中写入所需的信息,但没有取得积极的结果。

代码示例:(这里我们为每个容器生成随机uuid)

读取管道的代码

#define MAX_NUM_THREADS 3

void *ler_do_pipe(void *_fd) { //Reads from the pipes
    int fd;
    fd = (int) _fd;
    char buffer[4096];
    int n;
    while ((n = read(fd, buffer, 4096)) > 0) {
        write(1, buffer, n);
    }
}

int main() {
    pthread_t threads[MAX_NUM_THREADS];
    char fifo[5];
    int fd, i;

    for (i = 0; i < MAX_NUM_THREADS; i++) {
        sprintf(fifo, "fifo%d", i);
        fd = open(fifo, O_RDONLY); 
        pthread_create(&threads[i], NULL, ler_do_pipe, (void *)fd);  
    }

    pthread_exit(NULL);
    return 0; 
}

我用来编写管道的代码

/*writes to the respective pipe*/
void *escrever_para_pipe(void *_fd) {
    int fd;
    fd = (int) _fd;

    while(1) {
        char txt[43];

        /*criamos uma string do genero "uuid,destino" totalmente random */
    /*we create a string with the "serial Number,destination" all random*/
        sprintf(txt,"%s,%s\n",getuuid(),getPorto());

        write(fd, txt, 43);  
        sleep(2);
    }       
}

int main () {

    //We create 3 threads to the 3 pipes we have
    pthread_t threads[MAX_NUM_THREADS];
    char fifo[5];
    int fd, i;

    for (i = 0; i < MAX_NUM_THREADS; i++) {
        sprintf(fifo, "fifo%d", i);
        mkfifo(fifo, 0666);
    }

    for (i = 0; i < MAX_NUM_THREADS; i++) {
        sprintf(fifo, "fifo%d", i);
        fd = open(fifo, O_WRONLY); 
        pthread_create(&threads[i], NULL, escrever_para_pipe, (void*)fd);  
    }

    pthread_exit(NULL);
    return 0;
}

我希望信息会在管道和线程之间流动,但是我们无法连接它们。

0 个答案:

没有答案