Creation of Threads
A thread is an entity of a process that is the basic unit of CPU dispatch and dispatch, which is a smaller unit that can run independently than a process. The thread itself does not own the system resources, it has only a few resources (such as program counters, a set of registers and stacks) that are essential in the run, but it can share all the resources owned by the process with other threads belonging to one process.
Creation of ThreadsUse the Pthread_create function.
- #include <pthread.h>
- int pthread_create (pthread_t *__restrict __newthread, //newly created thread ID
- __const pthread_attr_t *__restrict __attr,//Thread Properties
- void * (*__start_routine) ( void *), // the newly created thread executes
- void *__restrict __arg) //parameters of the execution function
Return value: Success-0, failure-returns error number, can be used strerror (errno) function to get error message thread termination (three ways)
1. The thread returns from the execution function, and the return value is the thread's exit code
2. Threads are canceled by other threads in the same process
3. Call the Pthread_exit () function to exit. This is not called exit, because the thread calls the Exit function, which causes the process of the thread to exit.
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include < String.h>int num = 0;void *add (void *arg) {int i = 0, tmp; for (; i<500; i++) {tmp = num + i; num = tmp; printf ("add+1, result is%d\n", num); } return 0;} void *sub (void *arg) {int i = 0, tmp; for (; i<500; i++) {tmp = num-1; num = tmp; printf ("sub-1, result is%d\n", num); } return 0;} int main () {pthread_t tid_1, tid_2; int err; void *tret; Create Thread err = pthread_create (&tid_1, NULL, add, NULL); if (err! = 0) {printf ("pthread_create error.\n"); Exit (-1); Err = pthread_create (&tid_2, NULL, sub, NULL); if (err! = 0) {printf ("pthread_create error.\n"); Exit (-1); } err = Pthread_join (tid_1, &tret); if (err! = 0) {printf ("Pthread_join error.\n"); Exit (-1); } printf ("Thread 1 exit code%d\n", Tret); Err = Pthread_join (tid_2, &tret); if (err! = 0) {printf ("Pthread_join error.\n"); Exit (-1); } printf ("Thread 2 exit code%d\n", Tret);return 0;}
Compiled under Linux, g++-o thread1 thread1. C-lpthread
The result of the operation is not imaginary 0, because no lock is added ...
Multi-threaded Learning (i)