Thread Concept Definition
A thread is a flow of execution inside a process, and a process has at least one thread, and the thread has its own private resource and it shares resources with the process.
Thread-Unique Resources
- Thread descriptors
- Register
- Thread Stacks
- Errno
- Signal Mask
- Real-Time scheduling strategy
Resources shared by threads and processes
Creation of Threads
#include <pthread.h>int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
Parameters:
- Thread: Returns the ID of the thread
- attr: Thread properties can be set manually (the thread properties are described in detail below)
- Start_routine: Function Address of the function executed by the thread
- ARG: Parameters of the thread execution function
return value:
Successful return 0, failure returns error code. Termination of the threadThere are three ways of terminating a thread.
- Return with return.
- With Pthread_exit ();
#include <pthread.h>void pthread_exit(void *retval);
Parameters:
retval: Save thread exit code, <font color= "#dd00dd" > this pointer must be a global variable or a heap open. </font><br/>
- With Pthread_cancel ()
#include <pthread.h>int pthread_cancel(pthread_t thread);
Parameters:
Thread: End-of-Threads ID (can end any thread)
return value:
Successful return 0, failure returns error code.
The termination of a thread cannot be used with exit (), which is how the process terminates.
Why threads need to wait for a thread to wait and detach
- Does not wait, the resource is not freed automatically when the thread ends.
- Causes the multithreading descriptor to be consumed and the new thread cannot be created. Thread wait function
#include <pthread.h>int pthread_join(pthread_t thread, void **retval);
Parameters:
Thread: The ID of the waiting thread
RetVal: Save exit status Code
return value:
Successful return 0, failure returns error code.
Thread separationWe can use thread separation when we do not care about the exit state of the thread, just want the thread to end the system to automatically clean up and release the resources.
#include <pthread.h>int pthread_detach(pthread_t thread);
Parameters:
Thread: Detached thread ID
return value:
Successful return 0, failure returns error code.
Once a thread is separated by Pthread_detach (), it can no longer get its state by using Pthread_join (), and it can no longer return to the link state.
Thread PropertiesIn front of the pthread_create () function, the pthread_attr_t *attr thread properties are involved, and we can set the thread properties manually.
int pthread_attr_init(pthread_attr_t *attr);//初始化线程属性int pthread_attr_destroy(pthread_attr_t *attr);//销毁线程属性对象
Detach state = PTHREAD_CREATE_JOINABLE//分离属性int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);//设置分离属性int pthread_attr_getdetachstate(pthread_attr_t *attr, int *detachstate);//获得分离属性Scope = PTHREAD_SCOPE_SYSTEM//抢夺资源范围Inherit scheduler = PTHREAD_INHERIT_SCHED//是否继承线程调度策略Scheduling policy = SCHED_OTHER//调度策略Scheduling priority = 0//调度优先级Guard size = 4096 bytes//线程栈之间的安全区Stack address = 0x40196000//自己指定线程栈Stack size = 0x201000 bytes//栈的大小
Thread properties This piece, this article is just a simple list, a deeper grasp of the need for people to consult their own information.
Advantages of threads with advantages and disadvantages of threads
- The cost of creating a thread is much smaller than the cost of creating a process.
- Switching between threads has much less work to do than switching between processes.
- Threads consume much less resources than processes.
- Can take full advantage of the number of concurrent processors.
- When you wait for a slow I/O operation to finish, the program performs other compute tasks.
- Compute-intensive applications, multi-processor run, compute can be distributed across multiple threads.
- I/O intensive applications, in order to improve performance, overlap I/O operations, and threads can wait for different I/O operations. Disadvantages of threading
- Performance loss
- Decreased robustness.
- Lack of access control
- Increased programming difficulty
- Multithreaded support for GDB is not good
- Multithreading to signal support bad thread mutex mutex mutex
- Define mutex: pthread_mutex_t mutex;
- Initialization: Pthread_mutex_init (&mutex,null);
- Lock: Pthread_mutex_lock (&mutex);
- Unlock: Pthread_mutex_unlock (&mutex);
- Destroyed: Pthread_mutex_destroy (&mutex); spin lock
- Define spin Lock: pthread_spinlock_t spin;
- Initialize: int pthread_spin_init (pthread_spinlock_t *lock, int pshared);
- Lock: Int Pthread_spin_lock (pthread_spinlock_t *lock);
- Unlock: int pthread_spin_unock (pthread_spinlock_t *lock);
- Destroy Lock: int Pthread_spin_destroy (pthread_spinlock_t *lock);
The difference between spin lock and mutual exclusion lock
The difference between a spin lock and a mutex: the mutex is when the Pthread_mutex_lock is blocked, and the CPU is discarded so that others can use it. Spin lock blocking at Spin_lock, will not release the CPU, constantly ask the CPU can use the
Read/write Lock
- pthread_rwlock_t lock;
- Initialize: int pthread_rwlock_init (pthread_rwlock_t restrict rwlock,const pthread_rwlockattr_t restrict attr);
- Read lock: int pthread_rwlock_rdlock (pthread_rwlock_t *rwlock);
- Write Lock: int pthread_rwlock_wrlock (pthread_rwlock_t *rwlock);
- Unlock: int pthread_rwlock_unlock (pthread_rwlock_t *rwlock);
- Destroy Lock: int Pthread_rwlock_destroy (pthread_rwlock_t *rwlock);
Read-read sharing, read and write exclusive, write exclusive, write lock priority.
Synchronization condition Variable
- Define condition variables: pthread_cond_t cond;
- Initialize condition variable: int pthread_cond_init (pthread_cond_t restrict cond,const pthread_condattr_t restrict attr);
- Wait condition: int pthread_cond_wait (pthread_cond_t restrict cond,pthread_mutex_t restrict mutex);
If not used in the lock environment, the mutex is a dummy
If the mutex is unlocked in the context of a lock
When wait returns, the mutex is placed in its original state
- satisfies the condition: int pthread_cond_signal (pthread_cond_t *cond);
- Destroy condition variable: int Pthread_cond_destroy (pthread_cond_t *cond);
Comprehensive case
pthread_mutex_t mutex;//创建互斥量int a = 0;int b = 0;void *r1(void* arg) //线程1执行函数{ while(1) { pthread_mutex_lock(&mutex);//上锁 a++; b++; if(a != b) { printf("%d != %d\n",a,b); } pthread_mutex_unlock(&mutex);//解锁 }}void *r2(void* arg)//线程2执行函数{ while(1) { pthread_mutex_lock(&mutex); a++; b++; if(a != b) { printf("%d != %d\n",a,b); } pthread_mutex_unlock(&mutex); } }int main(void){ pthread_t t1,t2; pthread_mutex_init(&mutex,NULL);//初始化互斥量 pthread_create(&t1,NULL,r1,NULL);//创建线程 pthread_create(&t2,NULL,r2,NULL);//创建线程 pthread_join(t1,NULL);//线程等待 pthread_join(t2,NULL); return 0;}
Take you to learn multithreaded programming