Multi-threaded creation, exit, wait, delete syntax

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.