pthread kill after a certain time duration

跟風遠走 提交于 2020-01-05 19:28:10

问题


I'm working with VS2005 C++ and I'm BRAND NEW to it.

I have a loop that creates several threads using the following statement -

rc = pthread_create(&thread[i], NULL, &Function, (void *)threadID);

I want to terminate all threads after a certain duration (say 5 minutes). How do I have a timer that kills all threads after this duration?


回答1:


I believe, something like that:

pthread_t tid[thread_num] = {};
for(size_t i = 0 ; i < threads_num; ++i){
    pthread_create(&tid[i], NULL, func, arg);
}
sleep(300);
for(size_t i = 0 ; i < threads_num; ++i){
    pthread_cancel(tid[i]);
}

Anyway, I don't know how to use pthread under VS 2005 =)

Yes, one important point - to be killed, your threads should reach a cancellation point. Some POSIX functions could be cancellation points, but it's better to call pthread_testcancel() in your thread (as they work about minutes, I think it's some kind of loop, just check that every iteration)



来源:https://stackoverflow.com/questions/25389644/pthread-kill-after-a-certain-time-duration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!