当前位置:网站首页>A method of creating easy to manage and maintain thread by C language
A method of creating easy to manage and maintain thread by C language
2022-06-29 09:58:00 【Water like ice】
One 、 What is thread ?
Multiple execution routes in a program are called threads .
In terms of personal understanding , A thread is a thread in a process while(1), Generally, the thread will not exit .
Multithreading is naturally multiple threads in a process while(1) 了 .
《 Journey to the west 》 in , There is an interesting setting ——“ One day in the sky , On the ground a year ”.
And in the real world , With the development of technology ,CPU The performance of is getting higher and higher , Exaggeration point :“CPU A year , One day on the ground ”.
In order to make efficient use of CPU performance , The multi process approach enriches the operating system , Whether it's windows still Linux System , The procedures are “ shift ” Running , Slow down , That's it. Run it for a while , Then get out of the way CPU, Other programs run for a while , However, we seem to be running at the same time .
The same is true of multithreading .
Two 、linux Next thread function
Linux Multithreading under the system follows POSIX Thread interface , be called pthread. To write Linux Multithreading program under , You need to use a header file pthread.h, When compiling, pay attention to add -lpthread Parameters , To call the static link library ;pthread Is not Linux The default library of the system
1、pthread_create
- pthread_create yes UNIX Environment to create thread functions
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);- Return if successful 0, Otherwise, an error code is returned
- The first parameter is a pointer to the thread identifier ; Two parameters are used to set thread properties ; The third parameter is the address where the thread runs the function ; The last parameter is the parameter of the running function
2、pthread_join
- function pthread_join Used to wait for the end of a thread
extern int pthread_join __P (pthread_t __th, void **__thread_return);- If it works , Will return 0, If it fails, the error code will be returned
- The first parameter is the waiting thread identifier ; The second parameter is a user-defined pointer , It can be used to store the return value of the waiting thread .
- This function is a thread blocking function , The function that calls it will wait until the waiting thread ends , When the function returns , The resource of the waiting thread is recalled
#include <stdio.h>
#include <pthread.h>
void *threadfun(void *arg)
{
printf("hello \n");
}
int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,threadfun,NULL);
if(ret!=0) {
printf ("Create pthread error!\n");
exit (1);
}
pthread_join(id,NULL);
return (0);
} Add : printf("current thread id:%u\n", (unsigned int)pthread_self()); The current thread can be printed id.
3、 ... and 、 Create threads that are easy to manage and maintain
All documents are passed on by awesome colleagues . In case of loss and forgetting , So it's recorded here .
1、 advantage :
- Priority can be set
- Easy to view
2、 Use
Add the following in the project c Document and h file .
Header file , Then create :
static int port = 14000;
printf("current thread id:%u\n", (unsigned int)pthread_self());
ThreadCreateParaDef tThreadCreatePara;
memset(&tThreadCreatePara, 0, sizeof(ThreadCreateParaDef));
tThreadCreatePara.ps8Name = (char *)"receiveJobs";
tThreadCreatePara.pvFuncPara = &port;
tThreadCreatePara.EntryFuncPt = gSoapServerThread;
createThread(&tThreadCreatePara);3、 View steps
ps -ef | grep fw_ro* Check the process id
top -H -p 16002 View the thread of the process , The effect is as follows :
PID by 29527 The thread of is receiveJobs Threads . 
4、 appendix
cbasethread.h
#ifndef CBAETHREAD_H
#define CBAETHREAD_H
typedef struct ThreadCreateParaDef
{
char *ps8Name; // Thread name
void *(*EntryFuncPt)(void *); // Thread entry function
void *pvFuncPara; // Thread parameters
int s32OldCancelState;
int s32OldCancelType;
}ThreadCreateParaDef;
int CreateThread(ThreadCreateParaDef *ptThreadCreatePara);
#endif // MSG_DISTRIBUTION_Hcbasethread.c
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <memory.h>
#include <sys/prctl.h>
#include "cbasethread.h"
void *ThreadInterface(void *pvPara)
{
ThreadCreateParaDef *ptThreadCreatePara = (ThreadCreateParaDef *)pvPara;
void *pvFuncPara = ptThreadCreatePara->pvFuncPara;
/* Set this thread to Cancel Signal response ,state There are two kinds of value :PTHREAD_CANCEL_ENABLE( default ) and PTHREAD_CANCEL_DISABLE, After receiving the signal, they are set to CANCLED State and neglect CANCEL Letter No. 1 continues to run ;old_state If not for NULL Then save the original Cancel In order to recover . */
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &ptThreadCreatePara->s32OldCancelState);
/* Set the execution time of canceling action of this thread ,type There are two values :PTHREAD_CANCEL_DEFERRED and PTHREAD_CANCEL_ASYNCHRONOUS, Only when the Cancel Status as Enable Effective when , Respectively indicate receipt of After the signal, continue to run to the next cancellation point, exit and immediately execute the cancellation action ( sign out );oldtype Such as The result is not NULL Then save the value of the type of the cancelled action . */
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &ptThreadCreatePara->s32OldCancelType);
prctl(PR_SET_NAME, ptThreadCreatePara->ps8Name);
if(NULL != pvPara)
{
free(pvPara);
}
(*ptThreadCreatePara->EntryFuncPt)(pvFuncPara);
return NULL;
}
pthread_t TaskSpawn
(
char *ps8Name, /* The name of the task */
int s32Priority, /* Priority of real-time tasks 1-99 */
void *(*pvEntryPt)(void *), /* The function entry of the task */
void *pvFuncPara, /* This is a pointer value , Input parameters of the task entry function */
int s32Schedule /* Appoint fifo 、rr perhaps normal Scheduling method */
)
{
int ret = 0;
struct sched_param tSchParam;
pthread_attr_t tThreadAttr;
pthread_t tThreadID;
int s32SchPolicy;
if(NULL == pvEntryPt)
{
return 0;
}
/* Determine the correctness of priority */
if (s32Priority > 99 || s32Priority < 0)
{
return 0;
}
/* Initialize thread parameters */
pthread_attr_init(&tThreadAttr);
/* Set the scheduling policy */
pthread_attr_getschedpolicy(&tThreadAttr, &s32SchPolicy);
s32SchPolicy = s32Schedule; /* All tasks created will be real-time tasks */
pthread_attr_setschedpolicy(&tThreadAttr, s32SchPolicy);
/* Set the process to the detached state , After task separation, you will not need to use pthread_join() Wait for thread to exit */
pthread_attr_setdetachstate(&tThreadAttr, PTHREAD_CREATE_DETACHED);
if (SCHED_FIFO == s32Schedule || SCHED_RR == s32Schedule)
{
/* Set the priority of real-time tasks */
pthread_attr_getschedparam(&tThreadAttr, &tSchParam);
tSchParam.sched_priority = s32Priority;
pthread_attr_setschedparam(&tThreadAttr, &tSchParam);
}
ret = pthread_create(&tThreadID, &tThreadAttr, pvEntryPt, pvFuncPara);
if(0 != ret)
{
perror(NULL);
printf("TaskSpawn-%s create error", ps8Name);
return 0;
}
return tThreadID;
}
int CreateThread(ThreadCreateParaDef *ptThreadCreatePara)
{
pthread_t tThreadSysID;
ThreadCreateParaDef *pthreadPara = NULL;
pthreadPara = (ThreadCreateParaDef *)malloc(sizeof(ThreadCreateParaDef));
memcpy(pthreadPara, ptThreadCreatePara, sizeof(ThreadCreateParaDef));
tThreadSysID = TaskSpawn(ptThreadCreatePara->ps8Name, 1, ThreadInterface, pthreadPara, SCHED_RR);
if(!tThreadSysID) // There is a problem with thread startup
{
printf("Thread startup error\n");
if (pthreadPara != NULL)
{
free(pthreadPara);
}
return -1;
}
return 0;
}
边栏推荐
- Generic paging framework
- Middle order traversal of Li Kou 94 binary tree
- Fully Automated Gross Tumor Volume Delineation From PET in Head and Neck Cancer Using Deep Learning
- Gmail:如何快速将邮件全部已读
- Caused by: org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8
- 監控數據源連接池使用情况
- Automatic 3D Detection and Segmentation of Head and Neck Cancer from MRI Data.
- IDEA自动补全
- [noi Simulation Competition] add points for noi (heavy chain dissection, line segment tree)
- c语言printf大家族系列
猜你喜欢

Automatic Multi-Organ SegmVentation on Abdominal CT With Dense V-Networks

Kicad learning notes - shortcut keys

力扣94二叉树的中序遍历

基於PyQt5和Qt Designer的簡易加法計算器的制作

Lc236. nearest common ancestor of binary tree

你知道BFD是什么吗?一文详解BFD协议原理及使用场景
![[Huawei certification] the most complete and selected question bank in hcia-datacom history (with answer analysis)](/img/d4/f5ea847573433f7ca7bd429f57e40a.png)
[Huawei certification] the most complete and selected question bank in hcia-datacom history (with answer analysis)

Cisco ASA、FTD和HyperFlex HX的漏洞分析复现

UE4 compile a single file (VS and editor start respectively)

A 3D Dual Path U-Net of Cancer Segmentation Based on MRI
随机推荐
CROSSFORMER: A VERSATILE VISION TRANSFORMER BASED ON CROSS-SCALE ATTENTION
C # judge whether the array contains any items of another array
setInterval、setTimeout和requestAnimationFrame
Closed training (25) basic web security
FreeRTOS(八)——时间管理
1424. 对角线遍历 II
C语言实现一种创建易管理易维护线程的方法
动态规划总结
Official STM32 chip package download address stm32f10x stm32f40x Download
Closed door cultivation (24) shallow understanding of cross domain problems
A 2.5D Cancer Segmentation for MRI Images Based on U-Net
Construction and use of Changan chain go language smart contract environment
Monitoring data source connection pool usage
ImageView图片填充问题
基于stm32标准库独立按键的多按键状态机的实现
How to set Google Chrome as the default browser
kdevelop新建工程
Idea debugging fails, reporting jdwp no transports initialized, jvmtierror=agent_ ERROR_ TRANSPORT_ LOAD(196)
力扣85题最大矩形
F5 BIG-IP iControl REST命令执行(CVE-2022-1388)