繁体   English   中英

如何在另一个线程中暂停/中断boost :: thread?

[英]How can I pause/interrupt boost::thread within another thread?

void workerFunc()  //first thread
{  
    for (int x=0;x<30;x++) //count up to 29
    {
        cout << x << endl;
        Sleep(1000); //one sec delay
    }
}    

void test()   //second thread
{
    for (int y=30;y<99;y++)  //count up to 98
    {
        cout <<'\t'<< y << endl;        
        Sleep (1000); //delay one sec
    }
}

int main(int argc, char* argv[])   
{  
    cout << "Main started " << endl; 
    boost::thread workerThread(workerFunc);    //start the 1st thread
    boost::thread t1(test); //start the second thread
    cin.get();     
    return 0;  
}

您好,当线程用于test()其中y = 35,我要暂停/中断在线程workerFunc()线程内,用于test()

我该如何实现?

您可以使用boost::thread::interrupt 当目标线程准备好被中断时,它必须定期调用其中一个中断点函数 如果另一个线程调用boost::thread::interrupt ,则此函数将引发boost::thread_interrupted异常。 如果您的线程处于状态,则无法中断,但是您需要调用boost::thread::interrupt可以中断的函数之一,只需使用disable_interruption class暂时禁用中断即可。

在您的情况下,只需用boost::this_thread::sleep调用替换Sleep调用即可。

暂无
暂无

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

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