The threa_cancel() is used to cancel one particular thread by the thread id. This function sends one cancellation request to the thread for termination. The syntax of the pthread_cancel() is like below −
int pthread_cancel(pthread_t th);
登录后复制
现在,让我们看看如何使用这个函数来取消线程。
示例
#include #include #include #include int count = 0;pthread_t sample_thread;void* thread_one_func(void* p) { while (1) { printf("This is thread 1"); sleep(1); // wait for 1 seconds count++; if (count == 5) { //if the counter is 5, then request to cancel thread two and exit from current thread pthread_cancel(sample_thread); pthread_exit(NULL); } }}void* thread_two_func(void* p) { sample_thread = pthread_self(); //store the id of thread 2 while (1) { printf("This is thread 2
"); sleep(2); // wit for 2 seconds }}main() { pthread_t t1, t2; //create two threads pthread_create(&t1, NULL, thread_one_func, NULL); pthread_create(&t2, NULL, thread_two_func, NULL); //wait for completing threads pthread_join(t1, NULL); pthread_join(t2, NULL);}
登录后复制
输出
This is thread 2This is thread 1This is thread 1This is thread 2This is thread 1This is thread 1This is thread 1This is thread 2This is thread 2This is thread 2This is thread 2This is thread 2This is thread 2This is thread 2This is thread 2This is thread 2This is thread 2This is thread 2This is thread 2
登录后复制
以上就是在C语言中,pthread_cancel()函数的含义是取消一个线程的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2581619.html