简体   繁体   English

C ++中断线程等待用户输入

[英]C++ interrupt thread waiting for user-input

I have a problem, where I need to interrupt and wait for input. 我有一个问题,我需要中断并等待输入。 Any idea how to do this? 任何想法如何做到这一点?

bool run;
void partReceive() {
    while(run) {
        ...
        int rect_len = (int) recvfrom(servSockFD, buffer, 
              MAX_MESSAGE_LEN, 0, (struct sockaddr*) &newAddr, &slen);
        ...
    }
}

void partCount() {
    int i = 0;
    while(run) {
        i++;
        if (i >= 5) {
            run = false;
        }
    }
 }

 int main() {
       run = true;
       thread receive(partReceive);
       thread count(partCount);
       count.join();
       receive.join();
       return 0;
 }

This won't work, because partReceive() will hold until it receives input from socket.. 这将行不通,因为partReceive()会一直保持到从套接字接收到输入为止。

In addition to the existing answer, note that a useful design pattern is to use a pipe (or more precisely, a socketpair()), where main thread owns one end and the 'select thread' owns the other end. 除了现有答案外,请注意,有用的设计模式是使用管道(或更准确地说,是socketpair()),其中主线程拥有一端,而“选择线程”拥有另一端。 Then, to stop the 'select thread', you can send one character on the pipe (assuming the descriptor has been added to select). 然后,要停止“选择线程”,可以在管道上发送一个字符(假设已添加描述符以进行选择)。 This wakes up the thread that should be terminated (thread sleeps in select until something happens on the socket or on the control pipe). 这将唤醒应该终止的线程(线程在select中休眠,直到套接字或控制管道上发生问题)。

As suggested in the man page of recvfrom : recvfrom手册页中所建议:

You need to change receiver to first call select (see man page ) to check if there is something to read. 您需要将接收器更改为第一个呼叫select (请参见手册页 ),以检查是否有需要阅读的内容。 If there is something to read you can recvfrom knowing that it now will not block. 如果有东西可以读你可以recvfrom知道,它现在不会阻止。 select can also timeout if nothing is to be read. 如果不读取任何内容, select也会超时。 In that case you can at least check if you shall end the receiver thread. 在这种情况下,您至少可以检查是否应终止接收器线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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