通过printf和scanf进行线程通信(Linux) [英] Thread communication via printf and scanf (linux)

查看:135
本文介绍了通过printf和scanf进行线程通信(Linux)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Linux中工作并使用C ++. 我有一个启动线程的程序. 我需要主线程和子线程通过printf和scanf进行通信 (两个线程的代码都使用scanf和printf,并假定它与stdin和stdout通信.我必须保持这种方式). 我设法覆盖了printf和scanf,因此可以完全控制这些功能 (并且我可以使用* pthread_self *识别调用线程).

Working in Linux and using C++. I have a program which initiates a thread. I need the main thread and the child thread to communicate via printf and scanf (the code for both threads uses scanf and printf and assumes that it communicates with stdin and stdout. I must keep it that way). I managed to override printf and scanf, so I have total control over these functions (and I can identify the calling thread using *pthread_self*).

剩下要做的是创建2个文件句柄,一个用于通信的每个方向,并缓冲通信. 该怎么办?

What remains to be done is to create 2 file handles, one for each direction of the communication, and to buffer the communication. How can this be done?

在磁盘上写入文件并不能解决我的问题,因为通信时间可能很长,而且我无法将其存储在磁盘上.但是,我确实知道读取线程将在写入后不久读取数据,因此不需要很多缓冲.

Writing to a file on disk does not solve my problem as the communication may be very long and I can't afford to store it on disk. However, I do know that the reading thread will read the data not long after it's written, so not a lot of buffering is needed.

特别重要的是,如果一个线程调用 scanf(%s",& x),那么它将被阻塞,直到另一个线程写入一些字符串添加空格(因此字符串在完全写入之前不会被读取).

In particular, it is important that if one thread calls scanf("%s", &x) then it would be blocked until the other thread writes some string and adds whitespace (so the string is not read before it is completely written).

推荐答案

您可以使用管道. http://linux.die.net/man/2/pipe .您只需重定向stdout和stdin即可,而不是覆盖printf和scanf.但是请小心,因为printf和scanf不能重入.

You can use pipes. http://linux.die.net/man/2/pipe . You can simply redirect stdout and stdin instead of overriding printf and scanf. Be careful though, as printf and scanf are not re-entrant.

这篇关于通过printf和scanf进行线程通信(Linux)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆