简体   繁体   English

使用 C 中的线程实现 pipe

[英]Implementing pipe using threads in C

I am trying implement a pipe with functions read,write,close.我正在尝试实现具有读、写、关闭功能的 pipe。 My main creates 2 threads, one reads from an array and writes to pipe and the other read from pipe and writes to stdout.我的主线程创建了 2 个线程,一个从数组读取并写入 pipe,另一个从 pipe 读取并写入标准输出。 I am using a simple circular buffer as a pipe and I used Peterson's algorithm to synchronize the two of them.我使用一个简单的循环缓冲区作为 pipe 并且我使用彼得森的算法来同步它们两者。

My main should wait either for them to finish their operation or receive a "quit" input from stdin in which case it should call pipe_close() and terminate the 2 threads by causing them to return我的主程序应该等待他们完成操作或从标准输入接收“退出”输入,在这种情况下,它应该调用 pipe_close() 并通过使它们返回来终止 2 个线程

How am I supposed to get input from stdin without blocking?我应该如何在不阻塞的情况下从标准输入获取输入? How can I make the threads terminate?如何使线程终止? Should I use something like Lamports algorithm to synchronize all 3 of them?我应该使用 Lamports 算法之类的东西来同步所有 3 个吗?

Note: I can't use any functions from pthread.h except create注意:我不能使用 pthread.h 中的任何函数,除了 create

void *myread(void *par) {
  //read char from array store in c
  write_to_pipe(c)
}

void *mywrite(void *par) {
  read_from_pipe(&c);
  //print to stdout
}

main() {
  //create threads
  //wait until theads return or "quit" is written in stdin, call pipe_close and cause threads to return
}

Assuming you do not want to get into signals, and non-block IO, consider forking another thread that will wait for STDIN, and will notify the main three to exit.假设您不想进入信号,并且非阻塞 IO,请考虑分叉另一个等待 STDIN 的线程,并通知主三个退出。

This questions sounds like a school assignment.这个问题听起来像学校作业。 If it is, you should ask a teacher for help.如果是这样,你应该向老师寻求帮助。

You can't get input from stdin without blocking the thread that is reading from stdin .如果不阻塞从 stdin 读取的线程,就无法从stdin获取输入。 What I would do is set up two pointers for your circular buffer.我要做的是为您的循环缓冲区设置两个指针。 One for the stdin thread and one for the stdout thread.一个用于标准输入线程,一个用于标准输出线程。 After stdin has written data to the buffer it should update it's pointer to point to its last written element.标准输入将数据写入缓冲区后,它应该更新它的指针以指向其最后写入的元素。 stdout should be waiting until it sees that it's pointer is less than stdin 's pointer, and when this is the case it should write the elements of the buffer to stdout and update its own buffer after every write. stdout应该一直等到它看到它的指针小于stdin的指针,在这种情况下,它应该将缓冲区的元素写入stdout并在每次写入后更新自己的缓冲区。

This is basically Lamport's algorithm but for two threads, one producer and one consumer.这基本上是 Lamport 的算法,但有两个线程,一个生产者和一个消费者。

When one thread is reading or writing to/from the buffer you might need to block the other thread from reading/writing in order to eliminate race conditions in your code.当一个线程从缓冲区读取或写入/写入时,您可能需要阻止另一个线程读取/写入,以消除代码中的竞争条件。

Hope this helps.希望这可以帮助。

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

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