Talk C chestnuts together (109th back: C language instance -- thread creation and end 2)
Hello, the last time we talked aboutExample of thread creation and TerminationIn this case, let's continue with this example. When you leave the rest of your time, your words will go right. Let's talk C chestnuts together!
In the previous session, we introduced the usage of thread-related functions. In this session, we will use specific instances to describe how to use these functions to operate the threads.
Below isDetailed procedure:
1. define and implement the thread-executed function. Use the pthread_exit function in the function to end the thread. 2. use the pthread_create function to create a thread in the current process; 3. use the pthread_join function in the current process to wait for the end of the thread and obtain the status at the end of the thread;
The readers will not write the code in the text, and the detailed code will be put into my resources. You can download and use it.
In the program, the current process is the process where the main function is located, and the current thread is used in the main function to create a thread.
In the code, we defineTwo global variables:
One is used to save the state of the thread function; the other is the parameter of the thread function;
int status;char param[] = "Thread function param";
We modified the state of the thread function in the thread function and changed it from the initial value 0 to 3. The following is the code of the thread function:
void *thread_func(void *param) { printf("this is the function,it is running normally ."); printf("and the param is: %s \n",(char *)param); printf("The old status is %d \n",status); status = 3; // change the status; pthread_exit(&status); // end the thread }
Below isProgram running resultFor more information, see:
Create a thread this is the function, it is running normally. and the param is: Thread function param The old status is 0 thread function running finished and the status is: 3 // modified the status value in The Thread function
Let's talk about the example of thread creation and termination. I want to know what examples will be provided later, and I will try again.