1. Multithreading create pthread_create () syntax
2, multi-threaded exit pthread_exit () syntax
3. Multithreading waiting for Pthread_join () syntax
4. Multithreading delete Pthread_cancel () syntax
Code Analysis:
/*THREAD.C*/#include<stdio.h>#include<stdlib.h>#include<pthread.h>#defineThread_number 3/* Number of threads */#defineRepeat_number 5/* Number of small tasks per thread */#defineDelay_time_levels 10.0/* Maximum time interval between small tasks */void*thrd_func (void*Arg) { /*thread function Routines*/ intThrd_num = (int) Arg; intDelay_time =0; intCount =0; printf ("Thread%d is starting\n", Thrd_num); for(Count =0; Count < Repeat_number; count++) {Delay_time= (int) (rand () * delay_time_levels/(Rand_max)) +1; Sleep (Delay_time); printf ("\tthread%d:job%d delay =%d\n", Thrd_num, Count, Delay_time); } printf ("Thread%d finished\n", Thrd_num); Pthread_exit (NULL);}intMainvoid) {pthread_t thread[thread_number]; intNo =0, Res; void*Thrd_ret; Srand (Time (NULL)); for(No =0; No < Thread_number; no++) { /*Creating Multithreading*/Res= Pthread_create (&thread[no], NULL, Thrd_func, (void*) No); if(Res! =0) {printf ("Create thread%d failed\n", no); Exit (RES); }} printf ("Create Treads success\n waiting for threads to finish...\n"); for(No =0; No < Thread_number; no++) { /*wait for thread to end*/Res= Pthread_join (Thread[no], &Thrd_ret); if(!Res) {printf ("Thread%d joined\n", no); } Else{printf ("Thread%d join failed\n", no); } } return 0;}
Multi-threaded creation, exit, wait, delete syntax