c++ - 使用另一个线程停止 scanf 等待输入

标签 c++ c multithreading

我想从线程向主程序“发送消息”到 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,你应该使用 pipes,它是进程而非线程之间的通信工具

这是线程间通信的一种方式。读者线程代表您的 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)
        }
    }

关于c++ - 使用另一个线程停止 scanf 等待输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27584777/

相关文章:

c - 在 C 中使用 MPI_Type_Vector 和 MPI_Gather

c++ - 库会覆盖信号处理程序,但我需要按 CTRL+C 进行清理

c++ - 确定 minimax tic-tac-toe 中的正确位置

c++ - 初始化 vector 成员变量的正确方法

c - 进程在 C 中的父进程中挂起

c - 在 C 中使用 xmlReadFile 时出现警告/错误

c++ - 在我的 windows 和 mac 共享库中使用 openssl

c - 内存同步

c# - ThreadStatic、ThreadLocal、GetData 比为线程创建对象实例有什么优势?

c# - TaskFactory.Tasks 中 BlockingCollection.GetConsumingEnumerable() 集合的 Parallel.ForEach 和 foreach 循环