Threads with signals, threads and locks

Source: Internet
Author: User
Tags sigint signal

#include <stdio.h> #include <apue.h> #include <pthread.h>pthread_mutex_t Number_mutex = Pthread_ Mutex_initializer;int globvar = 0; void *write_p (void *arg) {while (1) {Pthread_mutex_lock (&numb        Er_mutex);        globvar++;        printf ("The Write is%ld\n", Globvar);        Pthread_mutex_unlock (&number_mutex);            Sleep (2);    }}void *read_p (void *arg) {int temp;        while (1) {printf ("The Read is%ld\n", pthread_self ());        Pthread_mutex_lock (&number_mutex);        printf ("read =%d\n", Globvar);        Sleep (10);              Pthread_mutex_unlock (&number_mutex);    }}int Main () {pthread_t thid1,thid2;    int err;    Err = Pthread_create (&thid1,null,read_p,null);    if (err! = 0) {printf ("The Pthread is error\n");    } sleep (1);    printf ("The Mid \ n");    Err = Pthread_create (&thid2,null,write_p,null);    printf ("Err is%d\n", err);  if (err! = 0) {printf ("The Pthread is error\n");  } while (1) {sleep (1);    }




#include <stdio.h> #include <apue.h> #include <pthread.h>pthread_mutex_t mutex;pthread_cond_t cond;    void *thread1 (void *arg) {pthread_cleanup_push (Pthread_mutex_unlock,&mutex);        while (1) {printf ("Thread1 is runing\n");        Pthread_mutex_lock (&mutex);        Pthread_cond_wait (&cond,&mutex);        printf ("Thread applied the condiation\n");        Pthread_mutex_unlock (&mutex);    Sleep (4); } pthread_cleanup_pop (0);}        void *thread2 (void *arg) {while (1) {printf ("Thread2 is runing\n");        Pthread_mutex_lock (&mutex);        Pthread_cond_wait (&cond,&mutex);        printf ("Thread2 application is condiation\n");        Pthread_mutex_unlock (&mutex);    Sleep (1);    }}int Main (void) {pthread_t tid1,tid2;    printf ("Condiation variable!\n");    Pthread_mutex_init (&mutex,null);    Pthread_cond_init (&cond,null);    Pthread_create (&tid1,null,thread1,null); Pthread_create (&tid2,null,tHread2,null);            do{pthread_cond_signal (&cond);    }while (1);    Sleep (50);    Pthread_exit (0); }


#include <stdio.h> #include <apue.h> #include <pthread.h>int quitflag;             Exit sign sigset_t mask;            Declares a signal set pthread_mutex_t lock = Pthread_mutex_initializer;           Initializes a mutex lock pthread_cond_t waitloc = Pthread_cond_initializer;    Initializes a condition variable void * THR_FN (void *arg)//processing signal for thread {int err;    int Signo;                         while (1) {err = sigwait (&mask,&signo);        Remove the signal screen Word if (err! = 0) {printf ("errpr\n");                                      } switch (Signo) {//Handle different signal case SIGINT:                Processing SIGINT signal printf ("interrupt\n");            break;                  Case Sigquit://Processing Sigquit signal pthread_mutex_lock (&lock);                               Lock Quitflag = 1; If this flag value is not changed, the loop Pthread_mutex_unlock will not be recalled (&loCK);              Unlock pthread_cond_signal (&waitloc);                Wait for the condition variable to cause wake-up at this time to block printf ("Case \ n");            return 0;                DEFAULT:PRINTF ("Unexpected signal%d\n", signo);        Exit (0);                                                        }}}int Main () {int err;                                       Standard error code sigset_t oldmask;                                       Declare the original signal set pthread_t tid;                                   Declares a thread number of sigemptyset (&mask);                                Clear signal Set Sigaddset (&mask,sigint);                               Add SIGINT Signal set Sigaddset (&mask,sigquit); Add Sigquit to the signal set if (err = Pthread_sigmask (sig_block,&mask,&oldmask))! = 0)//Add thread signal set the main thread begins to block these two signals in printf        ("printf Sig_block is error\n");               Err = Pthread_create (&tid,null,thr_fn,0); Creating a signal processing thread, the new thread inherits the original signal mask Word if (err! = 0) {printf ("creatE is error\n ");                                   } pthread_mutex_lock (&lock);        Locking while (Quitflag = = 0) {printf ("UST \ n");    Pthread_cond_wait (&waitloc,&lock);    } pthread_mutex_unlock (&lock);    printf ("Like May be\n");    Quitflag = 0;    printf ("Change the quitflag\n");    if (Sigprocmask (Sig_setmask,&oldmask,null) < 0)//Suggest to restore printf ("Sig_mask error") by line Cheng after completion of work; Exit (0);}

The reason for a quick mutex within a thread:
All resources of the thread are within the thread space, addressing only within the
Message Queuing and shared memory for a process are used by threads with ==> shared memory maximum benefit: independent of all processes
When the program goes wrong, the data in the shared memory will be saved in memory and will resume running when restarted.
Message Queuing: Standalone processes and threads, messages are bound to be received and processed (unless they are pipelining
Job) can be returned by itself. The thread and process that receives the message executes a handler for the message
Multitasking benefits: Simultaneous kernel processing-single-core tick processing
Thread's life is not independent


The reason the process is slower than the thread:
1) Process space Independent, requires the kernel as a transit
2) thread in the same process space, addressing memory continuous, all resources in the same process interval


Reasons for CPU core usage exceeding 100%:
Multi-core processing with a usage rate of more than 100% per CPU


Thread synchronization: Mutex


Type of Mutex:
Mutex = thread lock = Mutex
Thread lock, read and write locks, spin locks, condition variables <==> thread synchronization methods
@ Line Cheng class: 1) Normal lock 2) default lock 3) high speed lock 4) error Check lock 5) loopback lock
Locks are used for asynchronous
int Pthread_mutex_lock (pthread_mutex_t *mutex);
int Pthread_mutex_trylock (pthread_mutex_t *mutex);
int Pthread_mutex_unlock (pthread_mutex_t *mutex);
If the Pthread_mutex_trylock is invoked under blocked conditions, it will fail and cannot lock the mutex
Returns a ebusy that invokes the function to prevent deadlocks.
@ Line Cheng Initialization
With a lock on the wire, the lock is prepared for the thread.
If not initialized, the lock is locked and cannot be used.
int Pthread_mutex_destroy (pthread_mutex_t *mutex);
int Pthread_mutex_init (pthread_mutex_t *restrict Mutex,
Const pthread_mutexattr_t *restrict attr);
pthread_mutex_t mutex = Pthread_mutex_initializer;
Two ways to initialize:
1) Dynamic: int Pthread_mutex_init
2) Static: pthread_mutex_t mutex = Pthread_mutex_initializer;
If initialized to the default property, the attr value is null;
If the mutex is statically allocated, it is set to a constant pthread_mutex_initializer
@ Thread Lock use: First lock, then use, and then unlock.
The person who once had the lock has a greater chance of having the lock again without sleep, and if you sleep after unlocking,
The chance to grab the lock again is even.
When there is sleep, the time of the lock holder is prolonged, essentially another thread has a waiting time,
The time it takes for the lock to unlock again becomes shorter.
@10 seconds to detect if a deadlock is in:
GDB in the BT parameter view stack frame, view method:
1) View process number A) GDB Attach ID (process number)
b) Gdb-pid=id (process number)
2) bt View stack frame
3) View the value of the process stack frame local variable
Info threads
4) switch process thread Id (process number)
5) View stack space BT full
6) Exit Process Debug Detach
7) Exit GDB Q
@ generally said the thread lock refers to the default lock, can only be locked once; loopback Lock is a special
Can be locked multiple times, generally not used.
@ Spin Lock Properties
Spin Lock: If the spin lock is already held by another execution unit, the caller will always loop to see if the
The spin lock has already released the lock, "spin" is the meaning of the loop view.
@ Loopback lock can be locked multiple times, each time the counter plus one, reduce the use of locks, each minus a counter minus one
@1) Try to avoid multiple locks interspersed with
2) Reduce the branch of the lock
3) The thread lock must be declared before all functions are used, equivalent to a global variable
4) Global variables are mutually exclusive and cannot be substituted for locks. Global variables are not atoms, try not to use global variables
Alternative locks
@ Shorten the critical section length as much as possible, avoiding the second lock causing the program to hang (deadlock)
Instead of asynchronous mutex serial
The purpose of the @ Plus lock is to implement asynchronous mutex serial
@ Do not lock the method: Extend the resource to make the mutually exclusive objects more. such as: 10 threads corresponding to 10 resources.


Differences in semaphores, Message Queuing, and shared memory:
@ semaphore, Message Queuing is called by system call completion,
@ Shared memory only calls system calls at the time of application, and then in their own process range
It is highly efficient to operate with pointers.


At night also to see the use of dynamic library and loading, kernel--fork .... Spell it.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Threads with signals, threads and locks

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.