简体   繁体   中英

Stop scanf from waiting input, with another thread

I would like to "send a message" to scanf from a thread to the main program, I'm asking how to give to "scanf" function, or "cin" function, something to stop waiting.

You usually write something on the console and press "enter". How Can I do the same from another thread?

Example:

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

How can I achieve that??

As I understood you are tring to send information between threads. The official name is called Interthread Communication .

If you want to use scanf you should use pipes which is a communication tool between Processes not Threads

Here is a way you can communicate between threads. Reader threads represents your scanf thread. Writer thread represents mythread.

The system is simple. You have a shared memory. When one thread tries to write it, it locks the memory(which is queue in example) and writes. When the other one tries to read it, it again locks the memory and reads it and then deletes(pops from queue) it. If the queue is empty the reader thread waits until someone writes something in it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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