Ladies and gentlemen, crossing, the last time we were talking about the threading knowledge system diagram example, this time we say the example is: Multithreading. Gossip Hugh, words return to the positive. Let's talk C chestnuts together!
Crossing, I would first of all worship an old age, I wish you all good health and good luck in the new year.
Today we introduce multi-threading, I believe everyone has heard the term, but what is the specific meaning of it? In fact, multithreading refers to two or more than two threads running together, they work together to complete a job.
Our previous Zhanghuizhong introduced the use of the Pthread_create () function to create a thread. If you want to use multi-threading, you just need to use the function more than once to create a thread. Let's give an example to illustrate this.
The following is the core code:
while(Count >0) {Switch(count) { Case 1:strcpy(Param,"This is Thread:1"); Break; Case 2:strcpy(Param,"This is Thread:2"); Break; Case 3:strcpy(Param,"This is Thread:3"); Break; Case 4:strcpy(Param,"This is Thread:4"); Break; Case 5:strcpy(Param,"This is Thread:5"); Break;default: Break; } res = Pthread_create (&thread_value,null,thread_func, (void*) param);if(0! = Res) {printf("%s, it can ' t be created \ n", param);return 1; } Sleep (1); count--; }
We assign a value of 5 to count in the code, and then we create the thread through a looping statement so that 5 threads can be created. In addition, these threads share a thread function, except that the arguments passed to the function are different. Here is the code for this function, please refer to:
void *thread_func(void *param){ int status; printf("%s \n",(char *)param); // end the thread}
The function simply outputs the contents of the parameter to indicate that different threads are running and then ends the thread.
Crossing, the text will not write code, the completion of the code put in my resources, you can click here to download the use.
The following is the results of the operation of the program , please refer to:
Create multi is Thread:5 //第五个线程在运行is Thread:4 //第四个线程在运行 is Thread:3 //第三个线程在运行 is Thread:2 //第二个线程在运行 is Thread:1 //第一个线程在运行
You crossing, the example of multithreading we are here. We simply describe how to create multi-threading, but the most troublesome thing is how to dispatch multiple threads. Because thread scheduling involves operating system-related knowledge, it is not introduced for the time being. We will have a chance to introduce you to the knowledge of multi-thread scheduling. I want to know what the following example, and listen to tell.
Talk C Chestnut Bar (122th: C-language Instance-multithreading)