Maison  >  Article  >  développement back-end  >  Fonctions de thread en C/C++

Fonctions de thread en C/C++

PHPz
PHPzavant
2023-08-30 10:49:071040parcourir

Fonctions de thread en C/C++

Dans ce tutoriel, nous discuterons d'un programme pour comprendre les fonctions de thread en C/C++.

Les fonctions de threading permettent aux utilisateurs d'implémenter simultanément des fonctions concurrentes, qui peuvent dépendre les unes des autres pour l'exécution ou être indépendantes.

Exemple

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* func(void* arg){
   //detaching the current thread
   pthread_detach(pthread_self());
   printf("Inside the thread\n");
   pthread_exit(NULL);
}
void fun(){
   pthread_t ptid;
   //creating a new thread
   pthread_create(&ptid, NULL, &func, NULL);
   printf("This line may be printed before thread terminates\n");
   if(pthread_equal(ptid, pthread_self())
      printf("Threads are equal\n");
   else
      printf("Threads are not equal\n");
   //waiting for the created thread to terminate
   pthread_join(ptid, NULL);
   printf("This line will be printed" " after thread ends\n");
   pthread_exit(NULL);
}
int main(){
   fun();
   return 0;
}

Sortie

This line may be printed before thread terminates
Threads are not equal
Inside the thread
This line will be printed after thread ends

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer