[英]Stop scanf from waiting input, with another thread
我想“发送一条消息”以从线程到主程序的scanf,我在问如何赋予“ scanf”功能或“ cin”功能,以停止等待。
您通常在控制台上写一些东西,然后按“ Enter”。 如何从另一个线程执行相同操作?
例:
int main()
{
///// Some code to make the thread work ecc
std::cin >> mystring;
std::cout << mystring; // It should be "Text into mystring";
}
// From the other thread running...
void mythread()
{
std::string test = "Text into mystring";
// Write test to scanf! How?
}
我该如何实现?
据我了解,您正在尝试在线程之间发送信息。 正式名称称为Interthread Communication 。
如果要使用scanf,则应使用管道 ,这是进程之间而不是线程之间的通信工具
这是您可以在线程之间进行通信的一种方式。 阅读器线程代表您的scanf线程。 编写器线程代表mythread。
系统很简单。 您有共享的内存。 当一个线程尝试写入它时,它将锁定内存(在示例中为队列)并进行写入。 当另一个尝试读取它时,它再次锁定内存并读取它,然后将其删除(从队列中弹出)。 如果队列为空,则读取器线程将等到有人在其中写入内容。
struct MessageQueue
{
std::queue<std::string> msg_queue;
pthread_mutex_t mu_queue;
pthread_cond_t cond;
};
{
// In a reader thread, far, far away...
MessageQueue *mq = <a pointer to the same instance that the main thread has>;
std::string msg = read_a_line_from_irc_or_whatever();
pthread_mutex_lock(&mq->mu_queue);
mq->msg_queue.push(msg);
pthread_mutex_unlock(&mq->mu_queue);
pthread_cond_signal(&mq->cond);
}
{
// Main thread
MessageQueue *mq = <a pointer to the same instance that the main thread has>;
while(1)
{
pthread_mutex_lock(&mq->mu_queue);
if(!mq->msg_queue.empty())
{
std::string s = mq->msg_queue.top();
mq->msg_queue.pop();
pthread_mutex_unlock(&mq->mu_queue);
handle_that_string(s);
}
else
{
pthread_cond_wait(&mq->cond, &mq->mu_queue)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.