【发布时间】:2021-10-11 03:55:17
【问题描述】:
我有一个主线程,它创建子线程来执行各种任务。有一个子线程的任务是每 100 秒报告一次状态
我目前停止线程的机制是观察一个全局布尔值。有点像这样
子线程
void* ReportThread(bool* operation)
{
while(*operation)
{
// do its reporting task
// ........
int counter = 0;
while( counter < 100 && operation )
{
// let it sleep for 1 seconds and wake up to check
sleep(1);
sleepCounter += 1;
}
}
}
父(主)线程:
bool operation = false;
int main(){
pthread_t tid;
err = pthread_create(&tid), NULL, &ReportThread, &operation);
printf("Please input esc to end operation \n");
while ((ch = getchar()) != 27);
operation =true;
pthread_join(tid,NULL);
return 0;
}
问题:
- 似乎在使用 sleep(n)。秒数似乎很不一致。当程序停止时,该线程需要一段时间才能真正停止,可能需要 10 秒
- 有没有办法中断线程休眠?我听说你可以使用信号。我在 linux 中编码
- 我可以直接使用 pthread_cancel(tid) 代替 pthread_join(tid) 吗?
问候
【问题讨论】: