Heim >Backend-Entwicklung >C++ >In der C-Sprache besteht die Bedeutung der Funktion pthread_cancel() darin, einen Thread abzubrechen

In der C-Sprache besteht die Bedeutung der Funktion pthread_cancel() darin, einen Thread abzubrechen

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBnach vorne
2023-09-15 10:13:061263Durchsuche

In der C-Sprache besteht die Bedeutung der Funktion pthread_cancel() darin, einen Thread abzubrechen

Thread_cancel() wird verwendet, um einen bestimmten Thread anhand der Thread-ID abzubrechen. Diese Funktion sendet eine Abbruchanforderung an den Thread zur Beendigung. Die Syntax von pthread_cancel() ist wie folgt: −

int pthread_cancel(pthread_t th);

Nun sehen wir uns an wie man mit dieser Funktion einen Thread abbricht.

Beispiel

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
int count = 0;
pthread_t sample_thread;
void* thread_one_func(void* p) {
   while (1) {
      printf("This is thread 1</p><p>");
      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</p><p>");
      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);
}

Ausgabe

This is thread 2
This is thread 1
This is thread 1
This is thread 2
This is thread 1
This is thread 1
This is thread 1
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2
This is thread 2

Das obige ist der detaillierte Inhalt vonIn der C-Sprache besteht die Bedeutung der Funktion pthread_cancel() darin, einen Thread abzubrechen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:tutorialspoint.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen