13. Advanced IO and multithreading and thread synchronization

Source: Internet
Author: User

13.1. Blocking and non-blocking io
(1) Common blocking functions have wait+pause+sleep functions; Read or write some IO device files (such as serial/mouse/keyboard) can cause blocking The advantage of blocking is that the kernel operating system is simple and beneficial to the full performance of the CPU, and non-blocking IO is required when a thread operates multiple IO (for example, the mouse and keyboard simultaneously), and we can achieve non-blocking IO access through O_nonblock and Fcntl. The
(2) keyboard is the standard input device stdin (the corresponding FD is 0); the mouse corresponds to the/mouse0/mouse1/below the/dev/input directory. MOUSE2 (You can use cat to read the corresponding mouse file and then move the mouse to determine which mouse); If both the keyboard and mouse are read in the program, the user must follow the order of the program designed to read the keyboard and then read the mouse before operating the keyboard, This can cause the mouse and keyboard actions to be unrecognized, which is the dilemma of blocking IO.
(3) The solution for concurrent IO has a non-blocking io+ multiplexing io+ Asynchronous notification (asynchronous IO) in 3 ways; multi-path IO multiplexing (io_multiplexing) is typically used on multiple non-blocking IO ; Select and poll the two functions are used to implement IO multiplexing with the same idea, except that the two functions have different external characteristics (historical reasons) IO multiplexing is the principle of external blocking (the Select and poll functions themselves are blocked) while internal non-blocking automatic polling multiple blocking IO (the internal implementation of the Select and poll two functions is non-blocking). The
(4) can almost be considered asynchronous IO is the operating system with software implementation of the 1 sets of interrupt response system; Asynchronous IO works by our current process to register 1 asynchronous IO events (using signal to register 1 signal Sigio processing functions), and then the current process can normally handle its own things, When the asynchronous event occurs, the current process receives 1 Sigio signals to perform the binding handler function to handle the asynchronous event; The function involved has fcntl (F_getfl+f_setfl+o_async+f_setown) +signal/ Sigaction (Sigio). The
(5) stores the mapped Io;mmap function (mapping a file to a segment of memory). Mainly used in LCD display and IPC shared memory/Two processes of shared memory communication; storage mapping IO features = sharing rather than replication, reducing memory operations + high efficiency when handling large files, Small files are not cost-effective.

13.2. Comparison of processes and threads
(1) Advantages of using process technology = CPU-time Reuse single core CPU can realize the requirement of multitask system by multi process implementation (multi-task requirement is objective), and the disadvantage of process technology is the high switching overhead. interprocess communication is cumbersome and inefficient; the advantage of Threading Technology = thread technology retains process technology to implement multitasking features + threading improvement is the increase in the efficiency of thread switching and communication between threads + multithreading has the advantage over multiple core CPUs.
(2) threads in Linux = 1 lightweight processes + threads are the smallest unit + 1 processes that participate in kernel scheduling and can have multiple threads; The advantage of Threading Technology = threads can be easily efficiently communicated with the OS as a process and multiple threads of the same process + Multi-threaded technology can maximize program efficiency under the framework of multiple core CPUs (symmetric multiprocessor architecture SMP).
(3) thread-common functions; threads Create and recycle-pthread_create (the main thread is used to create child threads) +pthread_join (the main thread is used to wait (block) to reclaim the child thread) +pthread_detach (the main thread is used to detach the child thread). The main thread does not have to recycle the child thread after the separation; the-pthread_cancel (usually the main thread calls the function to cancel (Let it die) the child thread) +pthread_setcancelstate (the child thread sets itself whether it is allowed to be canceled) +pthread _setcanceltype (sets the type that the child thread is canceled); the thread function exits the associated-pthread_exit and return (exit) +pthread_cleanup_ Push (the child thread is locked while executing code is suddenly canceled by the main thread to guarantee the safe release of the lock and press the stack to unlock the function) +pthread_cleanup_pop (sub thread is locked while executing code without being canceled by the main thread the Unlock function determines whether the Unlock function is executed (see Figure 1) ; Gets the thread id-pthread_self.

13.3. Thread synchronization semaphore + Mutex + condition variable
(1) Thread synchronization is the need of the main thread and child threads to cooperate with each other; at ordinary times, child threads need to be blocked in a certain place, and then the main thread during normal operation if a certain condition can be signaled to activate the child thread execution, the child thread after the completion of the loop blocking wait to be activated by the main thread, the semaphore can be synchronized.
(2) The user enters any character from the terminal and then the statistic number displays, the input end ends; Using a multithreaded implementation that is the main thread gets the user input and determines whether to exit, the child thread is responsible for counting and printing the output.
(3) Mutual exclusion Lock is also called mutex (mutex), mutual exclusion lock related function Pthread_mutex_init+pthread_mutex_destroy+pthread_mutex_lock+pthread_mutex_unlock , it can be considered that the mutex is 1 kinds of special semaphore, strictly speaking, the mutex is only 0 and 12 states of the semaphore, the mutex is mainly used to achieve the protection of critical code segments, if the Man_3_pthread_mutex_init prompt can not find the function, Note the pthread-related man manual is not installed and can be downloaded using Sudo_apt-get_install_manpages-posix-dev.
(4) The condition variable is unique to the thread; First, we define 1 conditions globally, and then when a thread does not meet the condition, it causes the thread to block waiting for the condition, and then the other 1 threads meet a condition that sends a condition to block the thread that waits for the condition to activate it ; a condition variable is similar to asynchronous IO in process synchronization.
(5) The correlation function of the condition variable Pthread_cond_init+pthread_cond_destroy+pthread_cond_wait+pthread_cond_signal/pthread_cond_ Broadcast.

13.keyboard_mouse_io * * Company: XXXX * Author: Rston * Blog: Http://blog.csdn.net/rston * Github:https://github.com/rston * Project: High
 Level IO and multithreading and Thread synchronization * Features: Blocking-io+ non-blocking io+ multiplexing io+ asynchronous IO. * #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include & lt;unistd.h> #include <string.h> #include <stdlib.h> #include <sys/select.h> #include <sys/t
ime.h> #include <poll.h> #include <signal.h> typedef void (*sighandler_t) (int);

int mousefd =-1;
    #if 1//Sigio signal capture function void Signal_func (int sig) {char buf[1024] = {0};

    int ret =-1;

    if (Sig!= Sigio) return;
    ret = Read (MOUSEFD, buf, 8);
    if (Ret > 0) {printf ("The coment of Read Mouse is [%s].\n", buf);
    #endif int main (int argc, char **argv) {int FD =-1, ret =-1, flag =-1, i = 0;
    Char buf[1024];
    Fd_set RfDs;
    struct Timeval TV;

struct POLLFD pfds[2] = {0}; Simultaneous reading of keyboard device files and mouse device files demonstrates the plight of blocking IO #iF 0//Read mouse device file FD = open ("/dev/input/mouse0", o_rdonly);
        if (FD < 0) {perror ("open error");
    Exit (-1);
    } memset (buf, 0, sizeof (BUF));
    printf ("before read mouse.\n");
    Read (FD, buf, 8);

    printf ("The coment of Read Mouse is [%s].\n", buf);
    Read the keyboard device file memset (buf, 0, sizeof (BUF));
    printf ("before read keyboard.\n");
    Read (0, buf, 8);
printf ("The coment of Read keyboard is [%s].\n", buf); #endif//Simultaneous reading of keyboard device files and mouse device files demo non-blocking IO solution #if 0//Open mouse device file in non-blocking = open ("/dev/input/mouse0", o_rdonly |
    O_nonblock);
        if (FD < 0) {perror ("open error");
    Exit (-1);       Flag = fcntl (0, F_GETFL) of the default input stdin into a non-blocking type;             Get the original flag flag |= O_nonblock;        Add non-blocking Properties Fcntl (0, F_SETFL, flag);
        Update flag while (1) {memset (buf, 0, sizeof (BUF));
        ret = Read (FD, buf, 8); if (Ret > 0) {printf ("the ComeNT to read mouse is [%s].\n], buf);
        //Read keyboard device file memset (buf, 0, sizeof (BUF));
        ret = Read (0, buf, 8);
        if (Ret > 0) {printf ("The coment of Read keyboard is [%s].\n", buf);
    #endif//IO multiplexing simultaneously reads keyboard device files and mouse device files through the Select function #if 0 fd = open ("/dev/input/mouse0", o_rdonly);
        if (FD < 0) {perror ("open error");
    Exit (-1);
    ///Add FD and 2 files to RfDs Fd_zero (&AMP;RFDS);
    Fd_set (0, &rfds);

    Fd_set (FD, &rfds);
    Set timeout time to 5 seconds tv.tv_sec = 5;

    tv.tv_usec = 0;
    ret = Select (fd+1, &rfds, NULL, NULL, &AMP;TV);
        if (Ret < 0) {perror ("select Error");
    Exit (-1);
    else if (0 = ret) {printf ("Time out.\n"); 
            else {//detected keyboard input if (fd_isset (0, &rfds)) {memset (buf, 0, sizeof (BUF));
            Read (0, buf, 8); printf ("The coment of Read keyboard is [%s].\n ", buf);
            //detected mouse input if (Fd_isset (FD, &rfds)) {memset (buf, 0, sizeof (BUF));
            Read (FD, buf, 8);
        printf ("The coment of Read Mouse is [%s].\n", buf);
    } #endif//IO multiplexing simultaneously reads keyboard device files and mouse device files through the poll function #if 0 fd = open ("/dev/input/mouse0", o_rdonly);
        if (FD < 0) {perror ("open error");
    Exit (-1);             }//Initialize POLLFD PFDS[0].FD = 0;    Keyboard pfds[0].events = Pollin;            Wait read operation PFDS[1].FD = FD;    Mouse pfds[1].events = Pollin;
    Wait for read operation ret = poll (PFDs, fd+1, 5000);
        if (Ret < 0) {perror ("poll error");
    Exit (-1);
    else if (0 = ret) {printf ("Time out.\n"); else {//detected keyboard input or mouse input for (i=0 i<2; i++) {if (pfds[i].events = = PFD
                s[i].revents) {memset (buf, 0, sizeof (BUF));
      if (0 = i)          {Read (0, buf, 8);
                } if (1 = i) {read (FD, buf, 8);
            printf ("The coment of Read Mouse/keyboard is [%s].\n", buf);
    #if 1 MOUSEFD = open ("/dev/input/mouse0", o_rdonly) by using asynchronous IO to monitor the input of the mouse and keyboard at the same time #endif/
        if (MOUSEFD < 0) {perror ("open error");
    Exit (-1);
    ///Set the mouse file descriptor to accept asynchronous IO flag = fcntl (MOUSEFD, F_GETFL);
    Flag |= O_async;

    Fcntl (MOUSEFD, F_SETFL, flag);

    Set the receive process for the asynchronous IO event to the current process fcntl (MOUSEFD, F_setown, Getpid ());

    Registers the Sigio signal capture function of the current process signal (Sigio, signal_func);
        Reading keyboard device files while (1) {memset (buf, 0, sizeof (BUF));
        ret = Read (0, buf, 8);
        if (Ret > 0) {printf ("The coment of Read keyboard is [%s].\n", buf);
} #endif return 0; }
13.keyboard_mouse_thread * * Company: XXXX * Author: Rston * Blog: Http://blog.csdn.net/rston * Github:https://github.com/rston *
 Items: Advanced IO and multithreading and thread Sync * Features: Multi-process + multithreading. * #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #if 1 void *pthread_func (
    void *arg) {char buf[1024];
        Branch tasks, reading keyboard device files while (1) {memset (buf, 0, sizeof (BUF));
        printf ("before read keyboard.\n");
        Read (0, buf, 8);
    printf ("The coment of Read keyboard is [%s].\n", buf);
    #endif int main (int argc, char **argv) {int FD =-1;
    pid_t ret =-1;
    Char buf[1024];

pthread_t th =-1;
    Simultaneous reading of keyboard device files and mouse device files through multi-process technology #if 0 ret = fork ();
            if (Ret > 0) {//parent process, reading keyboard device file while (1) {memset (buf, 0, sizeof (BUF));
          printf ("before read keyboard.\n");  Read (0, buf, 8);
        printf ("The coment of Read keyboard is [%s].\n", buf);
        } else if (0 = = ret) {//subprocess, reading mouse device file FD = open ("/dev/input/mouse0", o_rdonly);
            if (FD < 0) {perror ("open error");
        Exit (-1);
            while (1) {memset (buf, 0, sizeof (BUF));
            printf ("before read mouse.\n");
            Read (FD, buf, 8);
        printf ("The coment of Read Mouse is [%s].\n", buf);
        } else {perror ("fork Error");
    Exit (-1); #endif//Simultaneous reading of keyboard device files and mouse device files through multithreading//GCC 13.keyboard_mouse_thread.c-pthread #if 1//Create thread read keyboard device file RET = Pthre
    Ad_create (&th, NULL, PTHREAD_FUNC, NULL);
        if (0!= ret) {printf ("pthread_create error.\n");
    return-1;
    //Because the child thread is a while (1) dead loop, it can be separated by the main thread, after which the main thread does not need to reclaim the child thread ret = pthread_detach (TH); if (0!= ret) {printf ("Pthread_detach error.\n");
    return-1;
    //main task, reading mouse device file FD = open ("/dev/input/mouse0", o_rdonly);
        if (FD < 0) {perror ("open error");
    return-1;
        while (1) {memset (buf, 0, sizeof (BUF));
        printf ("before read mouse.\n");
        Read (FD, buf, 8);
    printf ("The coment of Read Mouse is [%s].\n", buf);
#endif return 0; }
13.pthread_sem * * Company: XXXX * Author: Rston * Blog: Http://blog.csdn.net/rston * Github:https://github.com/rston * Project: Advanced IO and multi-line
 Thread Synchronization * Function: Demonstrates the synchronization problem between the main thread and the child thread through semaphore resolution. * #include <stdio.h> #include <string.h> #include <pthread.h> #include <stdlib.h> #include <
semaphore.h> char buf[1024] = {0};  
sem_t sem;      

unsigned int flag = 0;

    void *pthread_func (void *arg) {//thread blocking wait semaphore sem_wait (&AMP;SEM);
        while (0 = flag) {printf ("The CNTs of character is%d.\n", strlen (BUF));
        memset (buf, 0, sizeof (BUF));
    Thread blocking wait semaphore sem_wait (&AMP;SEM); 
}//Exit child thread Pthread_exit (NULL);
    int main (int argc, char **argv) {pid_t ret =-1;
    int value =-1;

    pthread_t th =-1;   
    Initialize semaphore value = Sem_init (&sem, 0, 0);
        if (0!= value) {perror ("Sem_init error");
    Exit (-1);
    ///Create sub-threading print output count function ret = pthread_create (&th, NULL, PTHREAD_FUNC, NULL); if (0!= RET) {printf ("pthread_create error.\n");
    return-1;
    printf ("Please input the character, input ' end ' stop.\n"); while (scanf ("%s", buf)) {if!strncmp (buf, ' End ', strlen ("End"))} {printf ("program sto
            P.\n ");
            flag = 1;
            Signal Volume plus 1, activate Sem_post (&AMP;SEM);
        Break
    //Semaphore plus 1, activate child thread sem_post (&AMP;SEM);
    }//Main thread Recycle sub-threads ret = pthread_join (th, NULL);
        if (0!= ret) {printf ("Pthread_join error.\n");
    Exit (-1);

    printf ("Pthread_join success.\n");
    The main thread destroys the signal quantity value = Sem_destroy (&sem);
        if (0!= value) {perror ("Sem_destroy error");
    Exit (-1);

    printf ("Sem_destroy success.\n");
return 0; }
13.pthread_mutex * * Company: XXXX * Author: Rston * Blog: Http://blog.csdn.net/rston * Github:https://github.com/rston * Project: Advanced IO and
 Multithreading and Thread Synchronization * Features: Demonstrates resolving the synchronization problem between the main thread and child threads through mutexes. * #include <stdio.h> #include <string.h> #include <pthread.h> #include <stdlib.h> #include <
unistd.h> char buf[1024] = {0};  
unsigned int flag = 0; 
int value =-1;

pthread_mutex_t Mutex;
    void *pthread_func (void *arg) {//ensures that the main thread is run to the locked Place Sleep (1) by CPU priority scheduling;
        while (0 = = flag) {//Lock value = Pthread_mutex_lock (&mutex);
            if (0!= value) {printf ("Pthread_mutex_lock error.\n");
        Exit (-1);
        printf ("The CNTs of character is%d.\n", strlen (BUF));
        memset (buf, 0, sizeof (BUF));
        Unlock value = Pthread_mutex_unlock (&mutex);
            if (0!= value) {printf ("Pthread_mutex_unlock error.\n");
        Exit (-1);
    }//Ensure that CPU scheduling main thread continues to run monitoring input sleep (1);}//Exit child thread Pthread_exit (NULL);
    int main (int argc, char **argv) {pid_t ret =-1;

    pthread_t th =-1;
    Initializes the creation of the Mutex value = Pthread_mutex_init (&mutex, NULL);
        if (0!= value) {printf ("Pthread_mutex_init error.\n");
    Exit (-1);
    ///Create sub-threading print output count function ret = pthread_create (&th, NULL, PTHREAD_FUNC, NULL);
        if (0!= ret) {printf ("pthread_create error.\n");
    return-1;
    printf ("Please input the character, input ' end ' stop.\n");
        while (1) {//Lock value = Pthread_mutex_lock (&mutex);
            if (0!= value) {printf ("Pthread_mutex_lock error.\n");
        Exit (-1);
        } scanf ("%s", buf);
        Unlock value = Pthread_mutex_unlock (&mutex);
            if (0!= value) {printf ("Pthread_mutex_unlock error.\n");
        Exit (-1);
     if (!strncmp (buf, "End", strlen ("End")) {        
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: