Create two threads to increase the number of threads.
Maybe this instance has no practical value, but with a slight change, we can use it elsewhere.
-
- # Include <pthread. h>
-
- # Include <stdio. h>
-
- # Include <sys/time. h>
-
- # Include <string. h>
-
- # Include <unistd. h>
- # Define max 10
-
- Pthread_tThread[2];
-
- Pthread_mutex_t mut;
-
- IntNumber = 0, I;
-
- Void* Thread1 (Void*)
-
- {
- Printf ("Thread1: I'm thread 1 \ n");
-
- For(I = 0; I <Max; I ++)
-
- {
-
- Printf ("Thread1: Number = % d \ n", Number );
- Pthread_mutex_lock (& MUT );
-
- Number ++;
-
- Pthread_mutex_unlock (& MUT );
-
- Sleep (2 );// The pthread_delay_np function can be used to sleep a thread for 2 seconds.
-
- }
- Printf ("Thread1: The main function is waiting for me? \ N");
-
- Pthread_exit (null );
-
- }
-
- Void* Thread2 (Void*)
-
- {
- Printf ("Thread2: I'm thread 2 \ n");
-
- For(I = 0; I <Max; I ++)
-
- {
-
- Printf ("Thread2: Number = % d \ n", Number );
- Pthread_mutex_lock (& MUT );
-
- Number ++;
-
- Pthread_mutex_unlock (& MUT );
-
- Sleep (3 );
-
- }
- Printf ("Thread2: The main function is waiting for me? \ N");
-
- Pthread_exit (null );
-
- }
-
- VoidThread_create (Void)
-
- {
- IntTemp;
-
- Memset (&Thread, 0,Sizeof(Thread));// Comment1
-
- /* Create thread */
- If(Temp = pthread_create (&Thread[0], null, thread1, null ))! = 0)// Comment2
-
- Printf ("Thread 1 fail to create! \ N");
-
- Else
- Printf ("Thread 1 created! \ N");
-
- If(Temp = pthread_create (&Thread[1], null, thread2, null ))! = 0)// Comment3
- Printf ("Thread 2 fail to create! ");
-
- Else
-
- Printf ("Thread 2 created! \ N");
-
- }
- VoidThread_wait (Void)
-
- {
-
- /* Wait thread end */
- If(Thread[0]! = 0 ){// Comment4
-
- Pthread_join (Thread[0], null );
- Printf ("Thread 1 completed \ n");
-
- }
-
- If(Thread[1]! = 0 ){// Comment5
- Pthread_join (Thread[1], null );
-
- Printf ("Thread 2 completed. \ n");
-
- }
-
- }
-
- IntMain ()
-
- {
- /* Init mutex */
-
- Pthread_mutex_init (& Mut, null );
-
- Printf ("Main function, creating thread... \ n");
-
- Thread_create ();
-
- Printf ("Main function, waiting for thread end... \ n");
- Thread_wait ();
-
- Return0;
-
- }
I am a main function. I am creating a thread, haha
thread 1 is created
thread 2 is created
I am the main function. I am waiting for the thread to complete the task. Haha
thread1: i'm thread 1
thread1: Number = 0
thread2: I'm thread 2
thread2: Number = 1
thread1: number = 2
thread2: Number = 3
thread1: Number = 4
thread2: Number = 5
thread1: Number = 6
thread1: number = 7
thread2: Number = 8
thread1: Number = 9
thread2: Number = 10
thread1: is the main function waiting for me to complete the task?
thread 1 has ended
thread2: is the main function waiting for me to complete the task?
thread 2 has ended