A process can contain multiple threads. The thread contains information required for the process execution environment, this includes the thread ID, a set of register values, stacks, scheduling priorities and policies, signal shielding characters, errno variables, and thread private data that identify a thread in a process. All information about a process is shared with all threads of the process, including executable program text, global memory and heap memory of the program, stack, and file descriptor.
Note that the process ID is globally unique, but the thread ID is valid only in the process environment to which it belongs.
Call the pthread_create function to create a thread (more information: man 3 pthread_create ):
1 #include <pthread.h>2 3 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);4 5 // Compile and link with -pthread
View Code
Here, the parameter arg is used as the passing parameter of the thread start function start_routine. If more than one parameter is passed, these parameters are placed in a struct, and the address of the structure is passed as the arg parameter.
Note: When a thread is created, it cannot be guaranteed which thread will run first: whether it is a newly created thread or a calling thread.
If any thread in the process calls exit, _ Exit, or _ exit, the whole process is terminated. Stop the entire process without terminating its control flow. A single thread can exit in the following three ways:
- If the thread returns from start_routine, the return value is the exit code of the thread;
- The thread can be canceled by other threads in the same process using the pthread_cancel function;
- The thread calls pthread_exit in start_routine.
Other threads in the same process can use the pthread_join function to obtain the exit code of the specified Thread (man 3 pthread_join ). If the second parameter of the function is set to NULL, The pthread_join function waits for the specified thread to terminate. By default, the state in the thread is saved to calling pthread_join for the thread. If the thread is already in the separation state, the underlying storage resources of the thread can be immediately withdrawn upon thread termination. When a thread is separated, the pthread_join function cannot be used to wait for its termination state.
Other threads in the same process can call the pthread_cancel function to cancel other threads in the same process.
The pthread_detach function can be used to separate threads.
Example(Linux instructions from pthread_create ):
1 #include <pthread.h> 2 #include <string.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <unistd.h> 6 #include <errno.h> 7 #include <ctype.h> 8 9 #define handle_error_en(en, msg) \ 10 do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) 11 12 #define handle_error(msg) \ 13 do { perror(msg); exit(EXIT_FAILURE); } while (0) 14 15 struct thread_info /* Used as argument to thread_start() */ 16 { 17 pthread_t thread_id; /* ID returned by pthread_create() */ 18 int thread_num; /* Application-defined thread # */ 19 char *argv_string; /* From command-line argument */ 20 }; 21 22 /* Thread start function: display address near top of our stack, 23 and return upper-cased copy of argv_string */ 24 25 static void * 26 thread_start(void *arg) 27 { 28 struct thread_info *tinfo = (struct thread_info *) arg; 29 char *uargv, *p; 30 31 printf("Thread %d: top of stack near %p; argv_string=%s\n", 32 tinfo->thread_num, &p, tinfo->argv_string); 33 34 uargv = strdup(tinfo->argv_string); 35 if (uargv == NULL) 36 handle_error("strdup"); 37 38 for (p = uargv; *p != '\0'; p++) 39 *p = toupper(*p); 40 41 return uargv; 42 } 43 44 int 45 main(int argc, char *argv[]) 46 { 47 int s, tnum, opt, num_threads; 48 struct thread_info *tinfo; 49 pthread_attr_t attr; 50 int stack_size; 51 void *res; 52 53 /* The "-s" option specifies a stack size for our threads */ 54 55 stack_size = -1; 56 while ((opt = getopt(argc, argv, "s:")) != -1) 57 { 58 switch (opt) 59 { 60 case 's': 61 stack_size = strtoul(optarg, NULL, 0); 62 break; 63 64 default: 65 fprintf(stderr, "Usage: %s [-s stack-size] arg...\n", 66 argv[0]); 67 exit(EXIT_FAILURE); 68 } 69 } 70 71 num_threads = argc - optind; 72 73 /* Initialize thread creation attributes */ 74 75 s = pthread_attr_init(&attr); 76 if (s != 0) 77 handle_error_en(s, "pthread_attr_init"); 78 79 if (stack_size > 0) 80 { 81 s = pthread_attr_setstacksize(&attr, stack_size); 82 if (s != 0) 83 handle_error_en(s, "pthread_attr_setstacksize"); 84 } 85 86 /* Allocate memory for pthread_create() arguments */ 87 88 tinfo = calloc(num_threads, sizeof(struct thread_info)); 89 if (tinfo == NULL) 90 handle_error("calloc"); 91 92 /* Create one thread for each command-line argument */ 93 94 for (tnum = 0; tnum < num_threads; tnum++) 95 { 96 tinfo[tnum].thread_num = tnum + 1; 97 tinfo[tnum].argv_string = argv[optind + tnum]; 98 99 /* The pthread_create() call stores the thread ID into100 corresponding element of tinfo[] */101 102 s = pthread_create(&tinfo[tnum].thread_id, &attr,103 &thread_start, &tinfo[tnum]);104 if (s != 0)105 handle_error_en(s, "pthread_create");106 }107 108 /* Destroy the thread attributes object, since it is no109 longer needed */110 111 s = pthread_attr_destroy(&attr);112 if (s != 0)113 handle_error_en(s, "pthread_attr_destroy");114 115 /* Now join with each thread, and display its returned value */116 117 for (tnum = 0; tnum < num_threads; tnum++)118 {119 s = pthread_join(tinfo[tnum].thread_id, &res);120 if (s != 0)121 handle_error_en(s, "pthread_join");122 123 printf("Joined with thread %d; returned value was %s\n",124 tinfo[tnum].thread_num, (char *) res);125 free(res); /* Free memory allocated by thread */126 }127 128 free(tinfo);129 exit(EXIT_SUCCESS);130 }
View Code
Running result: