Create N sub-threads in a loop of Linux programming and output implementation tutorials in sequence.

Source: Internet
Author: User

Create N sub-threads in a loop of Linux programming and output implementation tutorials in sequence.
Implementation Code

The Code is as follows. But there are also pitfalls! Parameters passed to the thread cannot traverse the I address cyclically. Because I is shared by multiple threads in the main thread, it is not unique. So how can each thread have its own sequential number?

1. Method 1: Of course, you can create a storage sequence number on the stack. Spaces with their own sequential numbers are independent of each other.

2. method 2: If the parameter is void *, you can directly pass the loop variable I to void *. Because arg is a variable in each thread stack space, it belongs to each sub-thread, then, it is strongly converted back to int when used, because void * and int are exactly 4 bytes, which is safe.

# Include
 
  
# Include
  
   
# Include
   
    
# Include
    
     
// Thread callback function void * myfun (void * arg) {// int num = (int) arg; // use the value transfer method, because the void * and int types are exactly four bytes, all of which can be converted to int num = * (int *) arg); sleep (num ); printf ("[% d] child thread id % lu \ n", num, pthread_self (); return NULL ;}int main (void) {pthread_t pthid [5]; int I; for (I = 0; I <5; I ++) {int * temp = (int *) malloc (sizeof (int); * temp = I; pthread_create (& pthid [I], NULL, myfun, (void *) temp); // pthread_create (& pthid [I], NULL, myfun, (void *) I ); // You can pass the value. Each thread stores its own stack space in a variety of sequences.} sleep (I ); // Let the thread print printf ("parent thread id % lu \ n", pthread_self (); return 0 ;}
    
   
  
 

Effect:

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.