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: