Threading Concepts
1. Threading is a lightweight process.
2. The thread shares the code snippet and data segment with the process that created it.
3. Threads have their own stand-alone stacks.
Threading Features
A thread can do the same or different work as a process, but shares resources with the process.
Thread Mutex
In real-world applications, multiple threads tend to access the same data or resource, and in order to avoid interaction between threads, it is necessary to introduce the thread mutex mechanism, which is one of the mutex (mutex) mutex mechanisms.
Thread.c
#include <pthread.h>#include<stdio.h>#include<unistd.h>pthread_mutex_t Mutex;intTask =0;void*thread0 ();void*thread1 ();voidMain () {//Creating Mutex LocksPthread_mutex_init (&mutex, NULL); //Creating child Threadspthread_t thread[2]; Pthread_create (&thread[0], NULL, THREAD0, NULL); Pthread_create (&thread[1], NULL, THREAD1, NULL); //waiting for a child threadPthread_join (thread[0], NULL); Pthread_join (thread[1], NULL);}void*thread0 () {//Show Threadsprintf"I am thread0!\n"); //Processing Tasks inti; for(i =0; I <Ten; i++){ //Get Mutex lockPthread_mutex_lock (&mutex); //Processing Taskstask++; //Release Mutex lockPthread_mutex_unlock (&mutex); //Show Tasksprintf"thread0 task:%d\n", Task); //Sleep WaitingSleep1); } //Exit ThreadPthread_exit (NULL);}void*Thread1 () {//Show Threadsprintf"I am thread1!\n"); //Processing Tasks inti; for(i =0; I <Ten; i++){ //Get Mutex lockPthread_mutex_lock (&mutex); //Processing Taskstask++; //Release Mutex lockPthread_mutex_unlock (&mutex); //Show Tasksprintf"Thread1 task:%d\n", Task); //Sleep WaitingSleep1); } //Exit ThreadPthread_exit (NULL);}
[Country EMBED strategy] [087] [Multithreaded Programming]