📜  C中的pthread_cancel()示例

📅  最后修改于: 2021-05-25 20:08:41             🧑  作者: Mango

先决条件:多线程,C中的pthread_self()(带示例)

pthread_cancel()=此函数使用线程ID取消特定线程。该函数向线程发送取消请求。

语法:– int pthread_cancel(pthread_t线程);

第一个程序:–取消自线程

// C program to demonstrates cancellation of self thread 
// using thread id
#include 
#include 
#include 
  
void* calls(void* ptr)
{
    printf("GeeksForGeeks");
  
    // To exit the current thread
    // pthread_self() return the particular thread id
    pthread_cancel(pthread_self()); 
      
    return NULL;
}
  
int main()
{
    // NULL when no attribute
    pthread_t thread;
  
    // calls is a function name
    pthread_create(&thread, NULL, calls, NULL); 
  
    // Waiting for when thread is completed
    pthread_join(thread, NULL); 
  
    return 0;
}

输出:

GeeksForGeeks

如果使用Linux,则编译该程序gcc program_name.c -lpthread

第二程序:–取消其他线程

// C program to demonstrates cancellation of another thread 
// using thread id
#include 
#include 
#include 
#include 
  
// To Count
int counter = 0; 
  
// for temporary thread which will be 
// store thread id of second thread
pthread_t tmp_thread; 
  
// thread_one call func
void* func(void* p) 
{
    while (1) {
  
        printf("thread number one\n");
        sleep(1);   // sleep 1 second
        counter++;   
        
        // for exiting if counter = = 5
        if (counter = = 2) {
  
            // for cancel thread_two
            pthread_cancel(tmp_thread); 
  
            // for exit from thread_one 
            pthread_exit(NULL);  
        }
    }
}
  
// thread_two call func2
void* func2(void* p) 
{
  
    // store thread_two id to tmp_thread
    tmp_thread = pthread_self(); 
  
    while (1) {
        printf("thread Number two");
        sleep(1); // sleep 1 second
    }
}
  
// Driver code
int main()
{
  
    // declare two thread
    pthread_t thread_one, thread_two; 
  
    // create thread_one
    pthread_create(&thread_one, NULL, func, NULL);
  
    // create thread_two 
    pthread_create(&thread_two, NULL, func2, NULL); 
  
    // waiting for when thread_one is completed
    pthread_join(thread_one, NULL); 
  
    // waiting for when thread_two is completed
    pthread_join(thread_two, NULL); 
  
}

输出:

thread number one
thread number two
thread number one 
thread number two

如果使用Linux,则编译该程序gcc program_name.c -lpthread

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。