当前位置:网站首页>Thread knowledge summary
Thread knowledge summary
2022-07-27 14:28:00 【amireux512】
Catalog
3, Recycling of thread resources
4, Synchronization mechanism between threads
3、 ... and , Mutually exclusive
One 、 The concept of thread
1, Threads are smaller units of activity than processes , It is an execution path in the process ( Take a branch ).
2, Threads share the address space of the process with other threads in the process .
==> Thread features :
1) Creating a thread is much less expensive than creating a process (why?)
because , Create a thread inside the process , There is no need to copy the address space of the whole process .
2) It is very convenient to realize the communication between threads , Because multiple threads created by a process directly share the memory area of the whole process .
3) Thread is also a dynamic concept .
4) Process is the smallest unit of operating system resource allocation , Thread is the smallest unit of scheduling .
5) Creating multithreads within a process , It can improve the parallel processing ability of the system , Speed up the process .
6) Each process will automatically have a main thread , Namely main function , If the main thread finishes executing , that
The process is over .
Two , Thread related API
1, Create a thread
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
Be careful : When compiling and linking, you need to add -pthread
2, Thread exit
There are three ways to end a thread :
(1) Thread function return
(2) Call middle note function pthread_exit()
void pthread_exit(void *retval);
@retval: The pointer , Used to return the return value . Equivalent to return Value after .
This value can be pthread_join() Function receive
(3) Called by another thread pthread_cancel Give you " Cancel " 了
int pthread_cancel(pthread_t thread);
@thread: Specify the thread to cancel ID
int pthread_setcancelstate(int state, int *oldstate);
@state : Cancel status attribute to set
PTHREAD_CANCEL_ENABLE Can be cancelled by others
PTHREAD_CANCEL_DISABLE Cannot be cancelled by others
@oldstate: Used to save the original cancellation status attribute
3, Recycling of thread resources
int pthread_join(pthread_t thread, void **retval);
@thread: Used to specify which thread to wait for to exit
@retval: It's a secondary pointer , The type of direction is void*, Used to save the return value of thread function
pthread_join Used to wait for a specified thread to exit , This function blocks the calling process , Until the waiting thread exits ,
It has two functions :
1) The blocking value is waiting for the thread to exit , And receive its return value
2) Reclaim the resources of the waiting thread
4, Synchronization mechanism between threads
1) Mutually exclusive
When multiple threads access a shared resource at the same time , We should “ Avoid competition ”
a. Semaphore mechanism
SYSTEM V Semaphore
POSIX Semaphore ( famous / unknown )
b. Thread mutex (pthread mutex)
2) Sync
==> Condition variables,
3、 ... and , Mutually exclusive
Thread mutex (pthread mutex) It is specially used to realize mutual exclusion between threads .
Its principle and function 、 The function is the same as the semaphore .
pthread_mutex_init Create a mutex
pthread_mutex_destroy Destroy a mutex
pthread_mutex_lock/trylock P operation
pthread_mutex_unlock V operation
Four , Sync
Synchronization between threads is achieved through conditional variables
Sync : Used to block a thread , Wake up another thread until it meets certain conditions .
==> etc.
pthread_cond_init Initialize a conditional variable
pthread_cond_destroy Destroy a conditional variable
pthread_cond_wait/timewait Blocking
pthread_cond_signal/broadcast Wake up the
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int a=0;
pthread_cond_t cond;
pthread_mutex_t mutex;
void* thread1(void* arg)
{
while(1)
{
printf("a:%d\n",a++);
sleep(1);
if(a>10)
{
pthread_mutex_lock(&mutex);//P operation
printf("A: the condition is ok, i wake up you!\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);//V operation
break;
}
}
}
void* thread2(void* arg)
{
if(a<=10)
{
printf("B: it's no condition, i sleep...\n");
pthread_mutex_lock(&mutex);//P operation
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);//V operation
printf("B: thank you very much!\n");
}
}
int main()
{
pthread_cond_init(&cond,NULL);
pthread_mutex_init(&mutex, NULL);
pthread_t tid1,tid2;
int r = pthread_create(&tid1,NULL,thread1,NULL);
if(r)
{
perror("pthread_create failed");
return -1;
}
r = pthread_create(&tid2,NULL,thread2,NULL);
if(r)
{
perror("pthread_create failed");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}
5、 ... and , Thread pool

pthread_pool.h
#ifndef __THREAD_POOL_H__
#define __THREAD_POOL_H__
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_TASK_NUM 10
#define SHUTDOWN_ON 0
#define SHUTDOWN_OFF 1
typedef struct node{
void *(*fun)(void *);// Task function pointer
void *arg; // Mission parameters
struct node *next;
}Node_thr;
typedef struct{
Node_thr *first;
Node_thr *last;
int NodeNum; // Number of nodes
int thr_Num; // Number of active threads
int shutdown; // Whether to turn off the thread pool flag bit , When shutdown by 1 Indicates that no more tasks are added to the thread pool
pthread_t *tid; // Save the active thread ID The first address of the address
pthread_mutex_t mutex;// Mutexes bound to conditional variables
pthread_cond_t cond;// Condition variables to realize synchronous operation
pthread_mutex_t mutex_head;// Save the mutex of the chain header node
}Head_thr; // Thread pool header
extern Head_thr *thread_pool_init(int thr_Num); // Initialize a thread pool
extern int finish_thread_pool(Head_thr *thread_pool); // Close a thread pool ( Waiting for the task to end , Destroy again )
extern int thread_pool_destroy(Head_thr *thread_pool); // Destroy a thread pool
extern int add_task(Head_thr *thread_pool,void *(*fun)(void *),void *arg); // Add tasks to the thread pool
extern int start_thread_pool(Head_thr *thread_pool); // Create all active threads
extern void *active_thread(void *arg); // The thread function corresponding to the active thread
#endifpthread_pool.c
#include "thread_pool.h"
// Initialize a thread pool
Head_thr *thread_pool_init(int thr_Num)
{
Head_thr *pool = malloc(sizeof(*pool));
pool->first = NULL;
pool->last = NULL;
pool->NodeNum = 0;
pool->shutdown = SHUTDOWN_OFF;
pool->thr_Num = thr_Num;
pool->tid = malloc(sizeof(pthread_t)*thr_Num);
pthread_mutex_init(&(pool->mutex),NULL);
pthread_mutex_init(&(pool->mutex_head),NULL);
pthread_cond_init(&(pool->cond),NULL);
return pool;
}
// Active thread function
void *active_thread(void *arg)
{
Head_thr *thread_pool = arg;
while(1)
{
pthread_mutex_lock(&(thread_pool->mutex_head));//P operation
if(thread_pool->shutdown==SHUTDOWN_ON && thread_pool->NodeNum==0)// wait for
{
pthread_mutex_unlock(&(thread_pool->mutex_head));//V operation
pthread_mutex_lock(&(thread_pool->mutex));//P operation
pthread_cond_wait(&(thread_pool->cond),&(thread_pool->mutex));// There are two places to wake up ==》1. New task 2. To turn it off
pthread_mutex_unlock(&(thread_pool->mutex));//V operation
pthread_mutex_lock(&(thread_pool->mutex_head));//P operation
}
if(thread_pool->shutdown==SHUTDOWN_OFF && thread_pool->NodeNum==0)// Exit thread
{
pthread_mutex_unlock(&(thread_pool->mutex_head));//V operation , It is forbidden to die with a lock
pthread_exit(NULL);
}
Node_thr *p = thread_pool->first;
thread_pool->first = thread_pool->first->next;
thread_pool->NodeNum--;
pthread_mutex_unlock(&(thread_pool->mutex_head));//V operation
p->fun(p->arg);// Perform tasks
free(p);
}
}
// Create all active threads
int start_thread_pool(Head_thr *thread_pool)
{
int r;
thread_pool->shutdown = SHUTDOWN_ON;
for(int i=0;i<thread_pool->thr_Num;i++)
{
r = pthread_create(thread_pool->tid+i,NULL,active_thread,thread_pool);
if(r != 0)
{
perror("pthread_create failed");
return r;
}
}
return 0;
}
// Close a thread pool ( Waiting for the task to end , Destroy again )
int finish_thread_pool(Head_thr *thread_pool)
{
thread_pool->shutdown = SHUTDOWN_OFF;
pthread_mutex_lock(&(thread_pool->mutex));//P operation
pthread_cond_broadcast(&(thread_pool->cond));// Wake up all threads
pthread_mutex_unlock(&(thread_pool->mutex));//V operation
for(int i=0;i<thread_pool->thr_Num;i++)// Wait until the active thread ends
{
pthread_join(thread_pool->tid[i], NULL);// The condition of thread end is :
//1, There are no tasks in the thread pool 2, My task is finished
}
return 0;
}
// Destroy a thread pool
int thread_pool_destroy(Head_thr *thread_pool)
{
free(thread_pool->tid);
free(thread_pool);
return 0;
}
// Add tasks to the thread pool
int add_task(Head_thr *thread_pool,void *(*fun)(void *),void *arg)
{
Node_thr *pnew = malloc(sizeof(*pnew));
pnew->fun = fun;
pnew->arg = arg;
pnew->next = NULL;
while(thread_pool->NodeNum >= MAX_TASK_NUM);// The queue node has reached the maximum , wait a minute
pthread_mutex_lock(&(thread_pool->mutex_head));//P operation
if(thread_pool->first == NULL)
{
thread_pool->first = pnew;
thread_pool->last = pnew;
}
else
{
thread_pool->last->next = pnew;
thread_pool->last = pnew;
}
thread_pool->NodeNum++;
pthread_mutex_unlock(&(thread_pool->mutex_head));//V operation
pthread_mutex_lock(&(thread_pool->mutex));//P operation
pthread_cond_signal(&(thread_pool->cond));
pthread_mutex_unlock(&(thread_pool->mutex));//V operation
return 0;
}
边栏推荐
- Travel notes from July 11 to August 1, 2022
- A Keypoint-based Global Association Network for Lane Detection
- Failed to connect to ResourceManager
- spark job 使用log4j appender 追加日志到本地文件或者mysql
- How to make computers have public IP
- 10 practical uses of NFT
- 线程知识总结
- Lesson 3: reverse word order
- Pure C handwriting thread pool
- watch VS watchEffect
猜你喜欢

一篇文章看懂JS执行上下文

GoPro access - control and preview GoPro according to GoPro official document /demo

10 practical uses of NFT
![[training day3] section [greed] [two points]](/img/4f/4130a1ade0ac0003adeddca780ff14.png)
[training day3] section [greed] [two points]

West test Shenzhen Stock Exchange listing: annual revenue of 240million, fund-raising of 900million, market value of 4.7 billion
![[luogu_p4820] [national training team] stack [mathematics] [physics] [harmonic progression]](/img/79/67399e6ce1908e38dc000e4b13a7ea.png)
[luogu_p4820] [national training team] stack [mathematics] [physics] [harmonic progression]

【STM32】EXTI
![[training day4] sequence transformation [thinking]](/img/2f/ab1ee75a871adfa9ad443c4a4886ae.png)
[training day4] sequence transformation [thinking]

Shell编程规范与变量

Slam overview Reading Note 4: a survey on deep learning for localization and mapping: towards the age of spatial 2020
随机推荐
PROFINET simulator tutorial
This points to problems, closures, and recursion
"Game engine light in light out" 4.1 unity shader and OpenGL shader
初学者入门:使用WordPress搭建一个专属自己的博客
WPF visifire.charts4.6.1 tutorial with source code
Lesson 3: reverse word order
Cognition -- classic of the road to success of hardware engineers
Ncnn compilation and use pnnx compilation and use
Windows10 installing SQL Server 2019
JS epidemic at home, learning can't stop, 7000 word long text to help you thoroughly understand the prototype and prototype chain
watch VS watchEffect
文献翻译__基于自适应全变差L1正则化的椒盐图像去噪
正掩码、反掩码、通配符
在Oracle VirtualBox中导入Kali Linux官方制作的虚拟机
第3章业务功能开发(添加线索备注,自动刷新添加内容)
Ten thousand words detailed Google play online application standard package format AAB
SLAM综述阅读笔记六:基于图像语义的SLAM调研:移动机器人自主导航面向应用的解决方案 2020
The difference between [x for X in list_a if not np.isnan (x)] and [x if not np.isnan (x) else none for X in list_a]
codeforces 1708E - DFS Trees
网上券商APP开户安全有保障吗?