当前位置:网站首页>Create thread: pthread_ create
Create thread: pthread_ create
2022-07-25 01:42:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack .
int pthread_create((pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) If the thread is created successfully , Then return to 0. If thread creation fails , The error number is returned , also *thread The content in is undefined
int pthread_join(pthread_t thread, void **retval); Wait in a blocked way thread The specified thread ends . When the function returns , The resource of the waiting thread is recalled . If the thread has ended , Then the function immediately returns . also thread The specified thread must be joinable Of
int pthread_detach(pthread_t tid); call pthread_join(pthread_id) after , If the thread does not end , The caller will be blocked , In some cases, we don't want this , For example Web In the server, when the main thread creates a sub thread for each new link to process , The main thread does not want to call pthread_join And jam ( Because we still need to continue to deal with the coming links ), At this time, you can add code to the sub thread pthread_detach(pthread_self()) Or the parent thread calls pthread_detach(thread_id)( Non blocking , You can return immediately )
pthread_t pthread_self(void); Get the thread's own ID.pthread_t The type of unsigned long int, So when printing, use %lu The way , Otherwise, there is something wrong with the display results .
void pthread_exit(void* retval); The thread calls pthread_exit Function terminates execution , Just as the process calls at the end exit The function is the same . The function is , Terminate the thread calling it and return a pointer to an object .
int pthread_cancel(pthread_t thread) Send a termination signal to thread Threads , Return if successful 0, Otherwise, it is not 0 value . Sending successfully does not mean thread Will be terminated . http://www.cnblogs.com/lijunamneg/archive/2013/01/25/2877211.html
int pthread_attr_init(pthread_attr_t *attr);int pthread_attr_destroy(pthread_attr_t *attr); The function is to initialize the properties of a thread object , Need to use pthread_attr_destroy Function to remove initialization . Posix Thread properties in threads pthread_attr_t It mainly includes scope attribute 、detach attribute 、 Stack address 、 Stack size 、 priority .
int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize); attr Is a thread property variable ;stacksize Is the set stack size . Return value 0,-1 It means success and failure respectively . The minimum stack value is defined as PTHREAD_STACK_MIN , contain #include <limits.h> After that, you can print its value to view . For default values, you can use pthread_attr_getstacksize (&attr, &stack_size); Print stack_size Check it out. .
int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy); Set thread scheduling policy ;POSIX The standard specifies three Scheduling Strategies : First in, first out strategy (SCHED_FIFO)、 Circular strategy (SCHED_RR) And custom policies (SCHED_OTHER).SCHED_FIFO Is a queue based scheduler , Different queues are used for each priority .SCHED_RR And FIFO be similar , The difference is that each thread of the former has an execution time quota .SCHED_FIFO and SCHED_RR It's right POSIX Realtime An extension of .SCHED_OTHER Is the default scheduling policy .
int pthread_attr_setscope (pthread_attr_t* attr, int scope); POSIX Two values are defined in the standard of :PTHREAD_SCOPE_SYSTEM and PTHREAD_SCOPE_PROCESS, The former means to compete with all threads in the system CPU Time , The latter means only competing with threads in the same process CPU. The default is PTHREAD_SCOPE_PROCESS.
int pthread_attr_setdetachstate (pthread_attr_t* attr, int detachstate); This indicates whether the new thread is out of sync with other threads in the process , If set to PTHREAD_CREATE_DETACHED The new thread cannot be used pthread_join() Synchronization , And release the occupied resources when exiting . Default is PTHREAD_CREATE_JOINABLE state . This property can also be used after the thread is created and run pthread_detach() To set up , And once it's set to PTHREAD_CREATE_DETACH state ( Whether it's a creation time setting or a runtime setting ) Can't recover to PTHREAD_CREATE_JOINABLE state .
int pthread_attr_setschedparam (pthread_attr_t* attr, struct sched_param* param);int pthread_attr_getschedparam (pthread_attr_t* attr, struct sched_param* param); One struct sched_param structure , There is only one sched_priority Integer variables indicate the priority of the thread . This parameter only if the scheduling strategy is real-time ( namely SCHED_RR or SCHED_FIFO) Only when effective , And can be run through pthread_setschedparam() Function to change , Default is 0
int pthread_setschedparam(pthread_t target_thread, int policy, const struct sched_param *param) Used to set the calling policy and priority of threads .
int pthread_attr_getinheritsched(const pthread_attr_t *attr,int *inheritsched);int pthread_attr_setinheritsched(pthread_attr_t *attr,int inheritsched);
Set inheritance properties of threads ,PTHREAD_INHERIT_SCHED: The new thread inherits the policies and parameters for creating the thread ;PTHREAD_EXPLICIT_SCHED: The new thread inheritance policy and parameter display specify .
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#ifndef T_DESC
#define T_DESC(x, y) (y)
#endif
#if T_DESC("global", 1)
pid_t gettid(void)
{
return syscall(SYS_gettid);
}
#endif
#if T_DESC("TU1", 1)
void thread_1(void)
{
int i;
for(i=0; i<10; i++) {
printf("thread_1: pid=0x%x tid=0x%x self=0x%x\n", getpid(), gettid(), (int)pthread_self());
sleep(1);
}
pthread_exit(0);
}
void thread_2(void)
{
int i;
for(i=0; i<5; i++) {
printf("thread_2: pid=0x%x tid=0x%x self=0x%x\n", getpid(), gettid(), (int)pthread_self());
sleep(1);
}
pthread_exit(0);
}
int tu1_proc(void)
{
pthread_t id_1,id_2;
int ret;
unsigned long stack_size;
pthread_attr_t attr;
struct sched_param sched;
pthread_attr_init(&attr);
sched.sched_priority = 80;
//pthread_attr_setschedpolicy(&attr, SCHED_OTHER);
pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
//pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); // It will cause thread creation failure
pthread_attr_getstacksize(&attr, &stack_size);
printf("default stack size is %ld(k)\n", stack_size/1024);
printf("SCHED_FIFO: Max %u, Min %u\n", sched_get_priority_max(SCHED_FIFO), sched_get_priority_min(SCHED_FIFO));
printf("SCHED_RR: Max %u, Min %u\n", sched_get_priority_max(SCHED_RR), sched_get_priority_min(SCHED_RR));
printf("SCHED_OTHER: Max %u, Min %u\n", sched_get_priority_max(SCHED_OTHER), sched_get_priority_min(SCHED_OTHER));
ret = pthread_create(&id_1, &attr, (void *)thread_1, NULL);
if(ret != 0)
{
printf("Create pthread error!\n");
return -1;
}
ret = pthread_create(&id_2, &attr, (void *)thread_2, NULL);
if(ret != 0)
{
printf("Create pthread error!\n");
return -1;
}
printf("main: pid=0x%x tid=0x%x self=0x%x\n", getpid(), gettid(), (int)pthread_self());
/* Wait for the thread to end */
pthread_join(id_1, NULL);
pthread_join(id_2, NULL);
return 0;
}
#endif
#if T_DESC("TU2", 1)
#endif
#if T_DESC("global", 1)
void usage()
{
printf("\n Usage: <cmd> <tu>");
printf("\n 1 -- base case");
printf("\n 2 -- todo ");
printf("\n");
}
int main(int argc, char **argv)
{
int ret;
if(argc < 2) {
usage();
return 0;
}
int tu = atoi(argv[1]);
if (tu == 1) ret = tu1_proc();
return ret;
}
#endif
#if T_DESC("readme", 1)
/*
1, compile command
gcc -o thread.out pthread.c -lpthread
*/
#endifPublisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/108577.html Link to the original text :https://javaforall.cn
边栏推荐
- Introduction to ORM framework - what is ORM framework?
- Harbor installation
- Antdb database products were selected into the global database industry map (2022) of the China Academy of communications and communications
- Harbor installation
- WhatsApp web for usability testing of software testing technology
- Kernel structure and design
- Pychart exits pytest mode (run pytest in mode)
- [C + + primer notes] Chapter 8 IO Library
- The difference between sigsuspend and sigwait
- Custom type
猜你喜欢

Cloud native platform, let edge applications play out!

Actf questions (dropper+master_of_dns)

Target segmentation for 10000 frames of video, less than 1.4GB of video memory, open source code | ECCV 2022
![[27. Expression evaluation (infix expression)]](/img/af/cf3c4a441232caeea9f9927ebdf87b.png)
[27. Expression evaluation (infix expression)]

The IPO of Tuba rabbit was terminated: the annual profit fell by 33%, and Jingwei Sequoia was the shareholder

What are the important trends revealed by the release of "operator data viability index"?

Beijing Zhun electric clock, Beidou clock server, GPS network time server, NTP satellite timing system

Alibaba cloud released the white paper "upgrade - standardization of data warehouse upgrade delivery"

EasyX realizes button effect

Custom type
随机推荐
Example analysis of recombinant monoclonal antibody prosci CD154 antibody
Ireport export PDF font bold failure
The difference between sigsuspend and sigwait
Pursue and kill "wallet Assassin" all over the network
MySQL series | log module
Point to point copy and paste of web pages
C traps and defects Chapter 2 lexical "traps" 2.4 switch statements
Download files and web pages with WGet
Take C language from 0 to 1 - program structure and use examples
Opengauss kernel analysis: query rewriting
Multi species tissue slide prosci pancreatic tissue solution
Worthington carboxyl transfer carbonic anhydrase application and literature reference
[27. Expression evaluation (infix expression)]
JS convert pseudo array to array
The introduction of 23 Filipino doctors for 18million was a hot topic, and the school teacher responded: expedient
Data integration | what are the tools for data integration at home and abroad?
Which bank outlet in Zhejiang can buy REITs fund products?
Plug ins QRcode and ityped
Service address dynamic awareness of Nacos registry
Peripherals: interrupt system of keys and CPU