开发者

Reading stdin from another thread

I am using p_threads in my code on unix. In my main program I have a thread Node which makes 2 threads one of which is doing a read from the standard input using getline. All of this working fine. Except at some point during my code I have to "restart my thread that reads from the standard input". And when i do that, my i am not able to read any thing from the stdin.

Any suggestions what i might be doing wrong ???/

Thanks.

This the part where i am reading from stdin

void* parseCmd(void* s) 
{

    sigset_t n开发者_StackOverflowew2; 
    struct sigaction act; 
    sigemptyset(&new2); 
    sigaddset(&new2,SIGINT); 
    pthread_sigmask(SIG_UNBLOCK, &new2, NULL); 

    act.sa_handler = interrupt; 
    sigaction(SIGINT, &act, NULL); 
    signal(SIGUSR1, signal_Handler);

    std::string input("");
    while (1) 
    {

       std::cout << "SERVANT > ";
       std::getline(std::cin, input);

       doTheWork(input);
       cin.clear();

       std::cout << std::endl;

      if(global_shutdown==1 || auto_global_shutdown==1)
        break;
    }


    cout<<"cmd thread exit.Main\n"; 
    return 0;

}


You are probably aborting the thread that is still connected to standard input, remember that you aborted the thread while doing getline.

Now I don't know if there is a way to acquire the standard input pointer and free it to be able to get more lines but there probably is a method to continue reading the lines tha previous thread has been reading.

What you need to do is:

  • when entering the getline use a shared flag and set it to true
  • set variable into which you read as a static variable and never use getline on it in any thread except the one that needs restarting
  • when you reconstruct the new thread do not call getline if the flag entering getline is true
  • after you finished getting the line reset the boolean flag
  • use locking to prevent concurrent acess on the reading line flag

When you need the value simply use the static variable that you use to pass to getline.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜