【问题标题】:Stop scanf from waiting input, with another thread使用另一个线程停止 scanf 等待输入
【发布时间】:2014-12-20 22:11:58
【问题描述】:

我想从线程向主程序“发送消息”给scanf,我在问如何给“scanf”函数或“cin”函数一些停止等待的东西。

您通常在控制台上写一些东西,然后按“回车”。 我怎样才能从另一个线程做同样的事情?

例子:

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?
}

我怎样才能做到这一点??

【问题讨论】:

  • 您的问题需要澄清一下。说“向scanf 发送消息”是没有意义的,而且,无论如何,您也不想将scanf 与C++ std::string 一起使用。我真的无法确定你在这里问什么。
  • @frasnian 已编辑。让我知道是否更清楚
  • std::cin 的输入通常来自键盘或其他文件,而不是程序本身。您是否只想使用来自mythread() 的字符串设置mystring。如果是这样,您应该使用std::async() 并使用get() 从返回的future 中获取值。有mythread()返回mystring

标签: c++ c multithreading


【解决方案1】:

据我了解,您正在尝试在线程之间发送信息。正式名称叫做Interthread Communication

如果你想使用scanf,你应该使用管道,它是进程而不是线程之间的通信工具

这是一种可以在线程之间进行通信的方式。阅读器线程代表您的 scanf 线程。 Writer线程代表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)
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    相关资源
    最近更新 更多