Threads with signals, threads and locks

Source: Internet
Author: User
Tags message queue mutex 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;           Initialize a mutually exclusive 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; Assume that this flag value is not changed. Does not bring up the Loop Pthread_mutex_unlock (&Lock);              Unlock pthread_cond_signal (&waitloc);                Wait for the condition variable to cause wake-up at this time to plug 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);                               Join SIGINT Signal Set Sigaddset (&mask,sigquit); Add sigquit into the signal set if (err = Pthread_sigmask (sig_block,&mask,&oldmask))! = 0)//join thread signal set the main thread starts plugging both signals 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)//After work is done, the line Cheng is restored to printf ("Sig_mask error"); Exit (0);}

Reasons why threads are mutually exclusive within a thread:
All of the threads ' resources are within thread space. Addressing is only within this thread
Process Message Queuing and shared memory are used by threads ==> shared memory Maximum advantage: independent of all processes
When the program is faulted. The data in the shared memory will be saved in memory. The execution state resumes after a restart.
Message Queuing: Standalone processes and threads, messages must be received and processed (unless pipelining
Working style) can return.

The thread and process that receives the message run the handler for the message one at a time
    Multitasking benefits: performing kernel processing at the same moment-single-core tick processing
    thread life is not independent


The reason the process is slower than the thread:
    1) process space is independent. Requires the kernel as a transit
    2) thread in the same process space, addressing memory continuity, all resources in the same process zone


Cup core usage exceeds 100% reason:
    multicore processing. The usage of each CPU is more than 100%


Thread synchronization: Mutually exclusive


Types of mutually exclusive amounts:
    Mutual repulsion = thread lock = Mutex
    Lock, read/write, spin lock, condition variable <==> thread synchronization
    @ line Cheng class: 1) Normal lock 2) default lock 3) Quick lock 4) error Check lock 5) loopback lock
    &NBSP ; 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);
      Call Pthread_mutex_trylock if it is plugged in. will fail and cannot lock the mutually exclusive amount
      return ebusy. Call this function to prevent deadlocks.
    Initialization of the @ line Cheng
      There is a lock on the wired thread. Locks are 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 static allocation of mutually exclusive amounts, it is set to a constant pthread_mutex_initializer
@ Thread Lock use: Lock first. Re-use, then unlock.
@ A person who has a lock has a greater chance of having a lock again after unlocking it without sleep;
The chance to grab the lock again is even.


When there is sleep, the lock holder is extended for the duration of the lock. In essence, other threads have a waiting time.
The time it takes for the lock to unlock again becomes shorter.


@10 seconds to detect whether the deadlock:
The BT reference in GDB 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 lock refers to the default locks, can only be locked once. A loopback lock is a special locking thread.
Can be locked multiple times, generally not used.
@ Spin Lock Properties
Spin Lock: Assuming that the spin lock has been maintained by another operating unit, the caller has been looping through the
The spin lock has already released the lock, "spin" is the meaning of the loop view.
The @ Loopback lock can be locked multiple times, plus one per additional counter. When the lock is used. Each time the counter is reduced by 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 variable implementations are mutually exclusive and cannot replace 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 asynchronously rejecting the serial with each other
The purpose of the @ Plus lock is to implement asynchronous mutually exclusive serial
@ Do not lock the method: The resource is expanded so that mutually exclusive objects become more.

such as: 10 threads corresponding 10 resources.


Differences in semaphores, Message Queuing, and shared memory:
@ semaphore, Message queue is call system call complete,
@ Shared memory is simply a call to the system at the time of application. And then they're in their own process range.
operate with a pointer. The efficiency is relatively high.



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.