1. summary :
The demo Mainly completed linux Lower thread creation , And resource recovery , Refer to related interface descriptions <<UNIX Environment advanced programming >>
2. test :
/* demo_pthread.c Thread programming demo : Thread creation , And resource recovery pthread be not Linux Default library of the system , But POSIX Thread library
stay Linux Use it as a library , So add -lpthread( or -pthread) To explicitly link the library */ #include <stdio.h> #
include <string.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h>
#include <sys/prctl.h> #define MAX_BUF 64 static void * pthread_fun(void *arg){
/* Thread rename */ prctl(PR_SET_NAME, "pthread_fun"); char buf[MAX_BUF]; #if 0 /*
Reclaim thread resources Set a non detached thread as a detached thread Notification thread library , Reclaim the memory and other resources occupied by the thread when the specified thread terminates */ pthread_detach(
pthread_self()); #endif memset(buf, 0x0, sizeof(buf)); memcpy(buf, (char *)arg,
strlen(arg)); /* Thread starts running */ printf("pthread start!\n"); printf("pthread id =
%lu\n", pthread_self()); printf("pthread buf = %s\n", buf); sleep(2); /* Thread end run
*/ printf("pthread end!\n"); pthread_exit((void *) 0); } int main(int argc, char
**argv){ void * ret; pthread_t pid; char buf[MAX_BUF]; /* Main thread starts running */ printf(
"main start!\n"); memset(buf, 0x0, sizeof(buf)); printf(" Please enter a message \t"); scanf("%s",
buf); /* Create thread */ if ((pthread_create(&pid, NULL, pthread_fun, (void*)buf)) != 0)
{ /* On execution error , Do not modify system global variables errno*/ printf("pthread_create err\n"); return -1; } /*
Wait for thread to end : The current thread will be blocked , Until the called thread ends , The current thread will continue to execute Reclaim thread resources : If the called thread is non detached ,
And is not used for this thread pthread_join() If , The thread does not free its memory space after it ends */ if (pthread_join(pid, &ret) != 0
){ printf("pthread_join err\n"); return -1; } printf("pthread ret = %ld\n", (
long)ret); /* Main thread ends running */ printf("main end!\n"); return 0; } #Makefile CC := gcc
INCLUDE= -I /home/demo/include/ LIB = -lpthread all: $(CC) demo_pthread.c $(
INCLUDE) $(LIB) -o demo_pthread -Wall -Werror clean: rm demo_pthread
Technology